[x86] invert logic for attribute 'FeatureFastUAMem'
[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->isTarget64BitLP64()) {
473     setExceptionPointerRegister(X86::RAX);
474     setExceptionSelectorRegister(X86::RDX);
475   } else {
476     setExceptionPointerRegister(X86::EAX);
477     setExceptionSelectorRegister(X86::EDX);
478   }
479   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
480   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
481
482   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
483   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
484
485   setOperationAction(ISD::TRAP, MVT::Other, Legal);
486   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
487
488   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
489   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
490   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
491   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
492     // TargetInfo::X86_64ABIBuiltinVaList
493     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
494     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
495   } else {
496     // TargetInfo::CharPtrBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
499   }
500
501   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
502   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
503
504   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
505
506   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
509
510   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511     // f32 and f64 use SSE.
512     // Set up the FP register classes.
513     addRegisterClass(MVT::f32, &X86::FR32RegClass);
514     addRegisterClass(MVT::f64, &X86::FR64RegClass);
515
516     // Use ANDPD to simulate FABS.
517     setOperationAction(ISD::FABS , MVT::f64, Custom);
518     setOperationAction(ISD::FABS , MVT::f32, Custom);
519
520     // Use XORP to simulate FNEG.
521     setOperationAction(ISD::FNEG , MVT::f64, Custom);
522     setOperationAction(ISD::FNEG , MVT::f32, Custom);
523
524     // Use ANDPD and ORPD to simulate FCOPYSIGN.
525     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
527
528     // Lower this to FGETSIGNx86 plus an AND.
529     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
531
532     // We don't support sin/cos/fmod
533     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
534     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
535     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
537     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
538     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
539
540     // Expand FP immediates into loads from the stack, except for the special
541     // cases we handle.
542     addLegalFPImmediate(APFloat(+0.0)); // xorpd
543     addLegalFPImmediate(APFloat(+0.0f)); // xorps
544   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545     // Use SSE for f32, x87 for f64.
546     // Set up the FP register classes.
547     addRegisterClass(MVT::f32, &X86::FR32RegClass);
548     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
549
550     // Use ANDPS to simulate FABS.
551     setOperationAction(ISD::FABS , MVT::f32, Custom);
552
553     // Use XORP to simulate FNEG.
554     setOperationAction(ISD::FNEG , MVT::f32, Custom);
555
556     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
557
558     // Use ANDPS and ORPS to simulate FCOPYSIGN.
559     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
561
562     // We don't support sin/cos/fmod
563     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
564     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
565     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
566
567     // Special cases we handle for FP constants.
568     addLegalFPImmediate(APFloat(+0.0f)); // xorps
569     addLegalFPImmediate(APFloat(+0.0)); // FLD0
570     addLegalFPImmediate(APFloat(+1.0)); // FLD1
571     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
573
574     if (!TM.Options.UnsafeFPMath) {
575       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
576       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
577       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
578     }
579   } else if (!Subtarget->useSoftFloat()) {
580     // f32 and f64 in x87.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
584
585     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
586     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
593       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
594       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
595       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
597     }
598     addLegalFPImmediate(APFloat(+0.0)); // FLD0
599     addLegalFPImmediate(APFloat(+1.0)); // FLD1
600     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
606   }
607
608   // We don't support FMA.
609   setOperationAction(ISD::FMA, MVT::f64, Expand);
610   setOperationAction(ISD::FMA, MVT::f32, Expand);
611
612   // Long double always uses X87.
613   if (!Subtarget->useSoftFloat()) {
614     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
617     {
618       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619       addLegalFPImmediate(TmpFlt);  // FLD0
620       TmpFlt.changeSign();
621       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
622
623       bool ignored;
624       APFloat TmpFlt2(+1.0);
625       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
626                       &ignored);
627       addLegalFPImmediate(TmpFlt2);  // FLD1
628       TmpFlt2.changeSign();
629       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
630     }
631
632     if (!TM.Options.UnsafeFPMath) {
633       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
634       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
635       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
636     }
637
638     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
640     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
642     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643     setOperationAction(ISD::FMA, MVT::f80, Expand);
644   }
645
646   // Always use a library call for pow.
647   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
648   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
649   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
650
651   setOperationAction(ISD::FLOG, MVT::f80, Expand);
652   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654   setOperationAction(ISD::FEXP, MVT::f80, Expand);
655   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
658
659   // First set operation action for all vector types to either promote
660   // (for widening) or expand (for scalarization). Then we will selectively
661   // turn on ones that can be effectively codegen'd.
662   for (MVT VT : MVT::vector_valuetypes()) {
663     setOperationAction(ISD::ADD , VT, Expand);
664     setOperationAction(ISD::SUB , VT, Expand);
665     setOperationAction(ISD::FADD, VT, Expand);
666     setOperationAction(ISD::FNEG, VT, Expand);
667     setOperationAction(ISD::FSUB, VT, Expand);
668     setOperationAction(ISD::MUL , VT, Expand);
669     setOperationAction(ISD::FMUL, VT, Expand);
670     setOperationAction(ISD::SDIV, VT, Expand);
671     setOperationAction(ISD::UDIV, VT, Expand);
672     setOperationAction(ISD::FDIV, VT, Expand);
673     setOperationAction(ISD::SREM, VT, Expand);
674     setOperationAction(ISD::UREM, VT, Expand);
675     setOperationAction(ISD::LOAD, VT, Expand);
676     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681     setOperationAction(ISD::FABS, VT, Expand);
682     setOperationAction(ISD::FSIN, VT, Expand);
683     setOperationAction(ISD::FSINCOS, VT, Expand);
684     setOperationAction(ISD::FCOS, VT, Expand);
685     setOperationAction(ISD::FSINCOS, VT, Expand);
686     setOperationAction(ISD::FREM, VT, Expand);
687     setOperationAction(ISD::FMA,  VT, Expand);
688     setOperationAction(ISD::FPOWI, VT, Expand);
689     setOperationAction(ISD::FSQRT, VT, Expand);
690     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691     setOperationAction(ISD::FFLOOR, VT, Expand);
692     setOperationAction(ISD::FCEIL, VT, Expand);
693     setOperationAction(ISD::FTRUNC, VT, Expand);
694     setOperationAction(ISD::FRINT, VT, Expand);
695     setOperationAction(ISD::FNEARBYINT, VT, Expand);
696     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697     setOperationAction(ISD::MULHS, VT, Expand);
698     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699     setOperationAction(ISD::MULHU, VT, Expand);
700     setOperationAction(ISD::SDIVREM, VT, Expand);
701     setOperationAction(ISD::UDIVREM, VT, Expand);
702     setOperationAction(ISD::FPOW, VT, Expand);
703     setOperationAction(ISD::CTPOP, VT, Expand);
704     setOperationAction(ISD::CTTZ, VT, Expand);
705     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706     setOperationAction(ISD::CTLZ, VT, Expand);
707     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708     setOperationAction(ISD::SHL, VT, Expand);
709     setOperationAction(ISD::SRA, VT, Expand);
710     setOperationAction(ISD::SRL, VT, Expand);
711     setOperationAction(ISD::ROTL, VT, Expand);
712     setOperationAction(ISD::ROTR, VT, Expand);
713     setOperationAction(ISD::BSWAP, VT, Expand);
714     setOperationAction(ISD::SETCC, VT, Expand);
715     setOperationAction(ISD::FLOG, VT, Expand);
716     setOperationAction(ISD::FLOG2, VT, Expand);
717     setOperationAction(ISD::FLOG10, VT, Expand);
718     setOperationAction(ISD::FEXP, VT, Expand);
719     setOperationAction(ISD::FEXP2, VT, Expand);
720     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725     setOperationAction(ISD::TRUNCATE, VT, Expand);
726     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729     setOperationAction(ISD::VSELECT, VT, Expand);
730     setOperationAction(ISD::SELECT_CC, VT, Expand);
731     for (MVT InnerVT : MVT::vector_valuetypes()) {
732       setTruncStoreAction(InnerVT, VT, Expand);
733
734       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
736
737       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738       // types, we have to deal with them whether we ask for Expansion or not.
739       // Setting Expand causes its own optimisation problems though, so leave
740       // them legal.
741       if (VT.getVectorElementType() == MVT::i1)
742         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
743
744       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745       // split/scalarized right now.
746       if (VT.getVectorElementType() == MVT::f16)
747         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748     }
749   }
750
751   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752   // with -msoft-float, disable use of MMX as well.
753   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755     // No operations on x86mmx supported, everything uses intrinsics.
756   }
757
758   // MMX-sized vectors (other than x86mmx) are expected to be expanded
759   // into smaller operations.
760   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
762     setOperationAction(ISD::AND,                MMXTy,      Expand);
763     setOperationAction(ISD::OR,                 MMXTy,      Expand);
764     setOperationAction(ISD::XOR,                MMXTy,      Expand);
765     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
766     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
767     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
768   }
769   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
770
771   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
773
774     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
779     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
780     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
781     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
784     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
785     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
787     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
788   }
789
790   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
792
793     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794     // registers cannot be used even for integer operations.
795     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
799
800     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
801     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
802     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
803     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
804     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
805     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
806     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
807     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
808     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
810     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
811     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
812     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
813     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
814     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
815     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
816     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
822     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
825     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
826     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
827     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
841     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
842     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
843     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
844
845     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
846     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
847       MVT VT = (MVT::SimpleValueType)i;
848       // Do not attempt to custom lower non-power-of-2 vectors
849       if (!isPowerOf2_32(VT.getVectorNumElements()))
850         continue;
851       // Do not attempt to custom lower non-128-bit vectors
852       if (!VT.is128BitVector())
853         continue;
854       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
855       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
856       setOperationAction(ISD::VSELECT,            VT, Custom);
857       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
858     }
859
860     // We support custom legalizing of sext and anyext loads for specific
861     // memory vector types which we can load as a scalar (or sequence of
862     // scalars) and extend in-register to a legal 128-bit vector type. For sext
863     // loads these must work with a single scalar load.
864     for (MVT VT : MVT::integer_vector_valuetypes()) {
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
866       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
867       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
874     }
875
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
877     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
879     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
880     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
881     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
882     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
883     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
884
885     if (Subtarget->is64Bit()) {
886       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
887       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
888     }
889
890     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
891     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
892       MVT VT = (MVT::SimpleValueType)i;
893
894       // Do not attempt to promote non-128-bit vectors
895       if (!VT.is128BitVector())
896         continue;
897
898       setOperationAction(ISD::AND,    VT, Promote);
899       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
900       setOperationAction(ISD::OR,     VT, Promote);
901       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
902       setOperationAction(ISD::XOR,    VT, Promote);
903       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
904       setOperationAction(ISD::LOAD,   VT, Promote);
905       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
906       setOperationAction(ISD::SELECT, VT, Promote);
907       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
908     }
909
910     // Custom lower v2i64 and v2f64 selects.
911     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
912     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
913     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
914     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
915
916     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
917     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
918
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
920
921     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
922     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
923     // As there is no 64-bit GPR available, we need build a special custom
924     // sequence to convert from v2i32 to v2f32.
925     if (!Subtarget->is64Bit())
926       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
927
928     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
929     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
930
931     for (MVT VT : MVT::fp_vector_valuetypes())
932       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
933
934     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
935     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
936     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
937   }
938
939   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
940     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
941       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
942       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
943       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
944       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
945       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
946     }
947
948     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
949     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
950     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
951     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
952     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
956
957     // FIXME: Do we need to handle scalar-to-vector here?
958     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
959
960     // We directly match byte blends in the backend as they match the VSELECT
961     // condition form.
962     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
963
964     // SSE41 brings specific instructions for doing vector sign extend even in
965     // cases where we don't have SRA.
966     for (MVT VT : MVT::integer_vector_valuetypes()) {
967       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
968       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
969       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
970     }
971
972     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
976     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
979
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
983     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
986
987     // i8 and i16 vectors are custom because the source register and source
988     // source memory operand types are not the same width.  f32 vectors are
989     // custom since the immediate controlling the insert encodes additional
990     // information.
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
995
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
997     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1000
1001     // FIXME: these should be Legal, but that's only for the case where
1002     // the index is constant.  For now custom expand to deal with that.
1003     if (Subtarget->is64Bit()) {
1004       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1005       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1006     }
1007   }
1008
1009   if (Subtarget->hasSSE2()) {
1010     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1011     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1012     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1013
1014     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1019
1020     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1022
1023     // In the customized shift lowering, the legal cases in AVX2 will be
1024     // recognized.
1025     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1026     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1027
1028     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1029     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1030
1031     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1033   }
1034
1035   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1036     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1039     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1040     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1042
1043     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1046
1047     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1057     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1058     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1059
1060     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1070     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1071     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1072
1073     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1074     // even though v8i16 is a legal type.
1075     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1077     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1078
1079     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1082
1083     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1084     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1085
1086     for (MVT VT : MVT::fp_vector_valuetypes())
1087       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1088
1089     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1090     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1091
1092     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1093     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1094
1095     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1099     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1100     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1101     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1102
1103     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1104     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1105     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1106
1107     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1108     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1109     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1110     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1111     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1112     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1113     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1114     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1115     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1116     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1117     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1118     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1119
1120     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1121     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1122     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1123     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1124
1125     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1126       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1127       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1128       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1129       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1130       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1132     }
1133
1134     if (Subtarget->hasInt256()) {
1135       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1136       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1137       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1138       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1139
1140       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1141       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1142       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1143       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1144
1145       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1146       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1147       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1148       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1149
1150       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1151       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1152       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1153       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1154
1155       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1156       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1157       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1158       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1159       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1160       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1161       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1167
1168       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1169       // when we have a 256bit-wide blend with immediate.
1170       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1171
1172       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1173       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1174       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1175       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1176       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1179
1180       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1182       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1183       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1186     } else {
1187       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1188       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1189       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1190       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1191
1192       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1193       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1194       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1195       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1196
1197       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1198       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1199       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1200       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1201
1202       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1203       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1204       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1205       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1206       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1207       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1208       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1209       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1210       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1211       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1212       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1213       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1214     }
1215
1216     // In the customized shift lowering, the legal cases in AVX2 will be
1217     // recognized.
1218     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1219     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1220
1221     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1222     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1223
1224     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1226
1227     // Custom lower several nodes for 256-bit types.
1228     for (MVT VT : MVT::vector_valuetypes()) {
1229       if (VT.getScalarSizeInBits() >= 32) {
1230         setOperationAction(ISD::MLOAD,  VT, Legal);
1231         setOperationAction(ISD::MSTORE, VT, Legal);
1232       }
1233       // Extract subvector is special because the value type
1234       // (result) is 128-bit but the source is 256-bit wide.
1235       if (VT.is128BitVector()) {
1236         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1237       }
1238       // Do not attempt to custom lower other non-256-bit vectors
1239       if (!VT.is256BitVector())
1240         continue;
1241
1242       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1243       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1244       setOperationAction(ISD::VSELECT,            VT, Custom);
1245       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1246       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1247       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1248       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1249       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1250     }
1251
1252     if (Subtarget->hasInt256())
1253       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1254
1255
1256     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1257     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1258       MVT VT = (MVT::SimpleValueType)i;
1259
1260       // Do not attempt to promote non-256-bit vectors
1261       if (!VT.is256BitVector())
1262         continue;
1263
1264       setOperationAction(ISD::AND,    VT, Promote);
1265       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1266       setOperationAction(ISD::OR,     VT, Promote);
1267       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1268       setOperationAction(ISD::XOR,    VT, Promote);
1269       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1270       setOperationAction(ISD::LOAD,   VT, Promote);
1271       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1272       setOperationAction(ISD::SELECT, VT, Promote);
1273       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1274     }
1275   }
1276
1277   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1278     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1279     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1280     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1281     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1282
1283     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1284     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1285     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1286
1287     for (MVT VT : MVT::fp_vector_valuetypes())
1288       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1289
1290     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1291     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1292     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1293     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1294     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1295     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1298     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1299     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1300     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1301     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1302
1303     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1304     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1305     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1306     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1307     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1308     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1309     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1310     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1311     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1315     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1316
1317     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1321     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1322     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1323
1324     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1328     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1329     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1330     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1331     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1332
1333     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1334     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1335     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1336     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1337     if (Subtarget->is64Bit()) {
1338       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1339       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1340       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1341       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1342     }
1343     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1345     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1346     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1347     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1349     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1352     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1354     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1357     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1358     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1359
1360     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1361     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1362     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1363     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1364     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1365     if (Subtarget->hasVLX()){
1366       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1367       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1368       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1369       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1370       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1371
1372       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1373       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1374       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1375       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1376       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1377     }
1378     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1379     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1380     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1381     if (Subtarget->hasDQI()) {
1382       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1383       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1384
1385       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1386       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1387       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1388       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1389       if (Subtarget->hasVLX()) {
1390         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1391         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1392         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1393         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1394         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1395         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1396         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1397         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1398       }
1399     }
1400     if (Subtarget->hasVLX()) {
1401       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1402       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1403       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1404       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1405       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1406       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1407       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1409     }
1410     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1411     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1412     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1413     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1414     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1415     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1416     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1417     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1418     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1419     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1420     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1422     if (Subtarget->hasDQI()) {
1423       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1424       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1425     }
1426     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1427     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1428     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1429     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1430     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1431     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1432     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1433     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1434     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1435     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1442
1443     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1444     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1445
1446     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1447
1448     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1450     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1452     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1454     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1459
1460     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1461     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1462     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1463     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1464     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1465     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1466     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1467     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1468
1469     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1470     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1471
1472     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1473     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1474
1475     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1476
1477     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1478     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1479
1480     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1481     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1482
1483     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1484     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1485
1486     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1487     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1488     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1489     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1490     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1491     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1492
1493     if (Subtarget->hasCDI()) {
1494       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1495       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1496     }
1497     if (Subtarget->hasDQI()) {
1498       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1499       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1500       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1501     }
1502     // Custom lower several nodes.
1503     for (MVT VT : MVT::vector_valuetypes()) {
1504       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1505       if (EltSize == 1) {
1506         setOperationAction(ISD::AND, VT, Legal);
1507         setOperationAction(ISD::OR,  VT, Legal);
1508         setOperationAction(ISD::XOR,  VT, Legal);
1509       }
1510       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1511         setOperationAction(ISD::MGATHER,  VT, Custom);
1512         setOperationAction(ISD::MSCATTER, VT, Custom);
1513       }
1514       // Extract subvector is special because the value type
1515       // (result) is 256/128-bit but the source is 512-bit wide.
1516       if (VT.is128BitVector() || VT.is256BitVector()) {
1517         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1518       }
1519       if (VT.getVectorElementType() == MVT::i1)
1520         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1521
1522       // Do not attempt to custom lower other non-512-bit vectors
1523       if (!VT.is512BitVector())
1524         continue;
1525
1526       if (EltSize >= 32) {
1527         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1528         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1529         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1530         setOperationAction(ISD::VSELECT,             VT, Legal);
1531         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1532         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1533         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1534         setOperationAction(ISD::MLOAD,               VT, Legal);
1535         setOperationAction(ISD::MSTORE,              VT, Legal);
1536       }
1537     }
1538     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1539       MVT VT = (MVT::SimpleValueType)i;
1540
1541       // Do not attempt to promote non-512-bit vectors.
1542       if (!VT.is512BitVector())
1543         continue;
1544
1545       setOperationAction(ISD::SELECT, VT, Promote);
1546       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1547     }
1548   }// has  AVX-512
1549
1550   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1551     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1552     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1553
1554     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1555     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1556
1557     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1558     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1559     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1560     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1561     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1562     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1563     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1564     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1565     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1566     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1567     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1568     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1569     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1570     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1571     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1572     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1573     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1574     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1575     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1576     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1577     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1578     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1579     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1580     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1581     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1582     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1583     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1584     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1585     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1586     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1587
1588     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1589     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1590     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1591     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1592     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1593     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1594     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1595     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1596
1597     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1598     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1599     if (Subtarget->hasVLX())
1600       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1601
1602     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1603       const MVT VT = (MVT::SimpleValueType)i;
1604
1605       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1606
1607       // Do not attempt to promote non-512-bit vectors.
1608       if (!VT.is512BitVector())
1609         continue;
1610
1611       if (EltSize < 32) {
1612         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1613         setOperationAction(ISD::VSELECT,             VT, Legal);
1614       }
1615     }
1616   }
1617
1618   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1619     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1620     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1621
1622     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1623     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1624     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1625     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1626     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1627     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1628     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1629     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1630     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1631     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1632
1633     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1634     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1635     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1636     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1637     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1638     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1639     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1640     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1641
1642     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1643     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1644     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1645     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1646     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1647     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1648     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1649     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1650   }
1651
1652   // We want to custom lower some of our intrinsics.
1653   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1654   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1655   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1656   if (!Subtarget->is64Bit())
1657     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1658
1659   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1660   // handle type legalization for these operations here.
1661   //
1662   // FIXME: We really should do custom legalization for addition and
1663   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1664   // than generic legalization for 64-bit multiplication-with-overflow, though.
1665   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1666     // Add/Sub/Mul with overflow operations are custom lowered.
1667     MVT VT = IntVTs[i];
1668     setOperationAction(ISD::SADDO, VT, Custom);
1669     setOperationAction(ISD::UADDO, VT, Custom);
1670     setOperationAction(ISD::SSUBO, VT, Custom);
1671     setOperationAction(ISD::USUBO, VT, Custom);
1672     setOperationAction(ISD::SMULO, VT, Custom);
1673     setOperationAction(ISD::UMULO, VT, Custom);
1674   }
1675
1676
1677   if (!Subtarget->is64Bit()) {
1678     // These libcalls are not available in 32-bit.
1679     setLibcallName(RTLIB::SHL_I128, nullptr);
1680     setLibcallName(RTLIB::SRL_I128, nullptr);
1681     setLibcallName(RTLIB::SRA_I128, nullptr);
1682   }
1683
1684   // Combine sin / cos into one node or libcall if possible.
1685   if (Subtarget->hasSinCos()) {
1686     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1687     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1688     if (Subtarget->isTargetDarwin()) {
1689       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1690       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1691       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1692       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1693     }
1694   }
1695
1696   if (Subtarget->isTargetWin64()) {
1697     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1698     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1699     setOperationAction(ISD::SREM, MVT::i128, Custom);
1700     setOperationAction(ISD::UREM, MVT::i128, Custom);
1701     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1702     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1703   }
1704
1705   // We have target-specific dag combine patterns for the following nodes:
1706   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1707   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1708   setTargetDAGCombine(ISD::BITCAST);
1709   setTargetDAGCombine(ISD::VSELECT);
1710   setTargetDAGCombine(ISD::SELECT);
1711   setTargetDAGCombine(ISD::SHL);
1712   setTargetDAGCombine(ISD::SRA);
1713   setTargetDAGCombine(ISD::SRL);
1714   setTargetDAGCombine(ISD::OR);
1715   setTargetDAGCombine(ISD::AND);
1716   setTargetDAGCombine(ISD::ADD);
1717   setTargetDAGCombine(ISD::FADD);
1718   setTargetDAGCombine(ISD::FSUB);
1719   setTargetDAGCombine(ISD::FMA);
1720   setTargetDAGCombine(ISD::SUB);
1721   setTargetDAGCombine(ISD::LOAD);
1722   setTargetDAGCombine(ISD::MLOAD);
1723   setTargetDAGCombine(ISD::STORE);
1724   setTargetDAGCombine(ISD::MSTORE);
1725   setTargetDAGCombine(ISD::ZERO_EXTEND);
1726   setTargetDAGCombine(ISD::ANY_EXTEND);
1727   setTargetDAGCombine(ISD::SIGN_EXTEND);
1728   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1729   setTargetDAGCombine(ISD::SINT_TO_FP);
1730   setTargetDAGCombine(ISD::UINT_TO_FP);
1731   setTargetDAGCombine(ISD::SETCC);
1732   setTargetDAGCombine(ISD::BUILD_VECTOR);
1733   setTargetDAGCombine(ISD::MUL);
1734   setTargetDAGCombine(ISD::XOR);
1735
1736   computeRegisterProperties(Subtarget->getRegisterInfo());
1737
1738   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1739   MaxStoresPerMemsetOptSize = 8;
1740   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1741   MaxStoresPerMemcpyOptSize = 4;
1742   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1743   MaxStoresPerMemmoveOptSize = 4;
1744   setPrefLoopAlignment(4); // 2^4 bytes.
1745
1746   // Predictable cmov don't hurt on atom because it's in-order.
1747   PredictableSelectIsExpensive = !Subtarget->isAtom();
1748   EnableExtLdPromotion = true;
1749   setPrefFunctionAlignment(4); // 2^4 bytes.
1750
1751   verifyIntrinsicTables();
1752 }
1753
1754 // This has so far only been implemented for 64-bit MachO.
1755 bool X86TargetLowering::useLoadStackGuardNode() const {
1756   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1757 }
1758
1759 TargetLoweringBase::LegalizeTypeAction
1760 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1761   if (ExperimentalVectorWideningLegalization &&
1762       VT.getVectorNumElements() != 1 &&
1763       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1764     return TypeWidenVector;
1765
1766   return TargetLoweringBase::getPreferredVectorAction(VT);
1767 }
1768
1769 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1770                                           EVT VT) const {
1771   if (!VT.isVector())
1772     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1773
1774   const unsigned NumElts = VT.getVectorNumElements();
1775   const EVT EltVT = VT.getVectorElementType();
1776   if (VT.is512BitVector()) {
1777     if (Subtarget->hasAVX512())
1778       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1779           EltVT == MVT::f32 || EltVT == MVT::f64)
1780         switch(NumElts) {
1781         case  8: return MVT::v8i1;
1782         case 16: return MVT::v16i1;
1783       }
1784     if (Subtarget->hasBWI())
1785       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1786         switch(NumElts) {
1787         case 32: return MVT::v32i1;
1788         case 64: return MVT::v64i1;
1789       }
1790   }
1791
1792   if (VT.is256BitVector() || VT.is128BitVector()) {
1793     if (Subtarget->hasVLX())
1794       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1795           EltVT == MVT::f32 || EltVT == MVT::f64)
1796         switch(NumElts) {
1797         case 2: return MVT::v2i1;
1798         case 4: return MVT::v4i1;
1799         case 8: return MVT::v8i1;
1800       }
1801     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1802       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1803         switch(NumElts) {
1804         case  8: return MVT::v8i1;
1805         case 16: return MVT::v16i1;
1806         case 32: return MVT::v32i1;
1807       }
1808   }
1809
1810   return VT.changeVectorElementTypeToInteger();
1811 }
1812
1813 /// Helper for getByValTypeAlignment to determine
1814 /// the desired ByVal argument alignment.
1815 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1816   if (MaxAlign == 16)
1817     return;
1818   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1819     if (VTy->getBitWidth() == 128)
1820       MaxAlign = 16;
1821   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1822     unsigned EltAlign = 0;
1823     getMaxByValAlign(ATy->getElementType(), EltAlign);
1824     if (EltAlign > MaxAlign)
1825       MaxAlign = EltAlign;
1826   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1827     for (auto *EltTy : STy->elements()) {
1828       unsigned EltAlign = 0;
1829       getMaxByValAlign(EltTy, EltAlign);
1830       if (EltAlign > MaxAlign)
1831         MaxAlign = EltAlign;
1832       if (MaxAlign == 16)
1833         break;
1834     }
1835   }
1836 }
1837
1838 /// Return the desired alignment for ByVal aggregate
1839 /// function arguments in the caller parameter area. For X86, aggregates
1840 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1841 /// are at 4-byte boundaries.
1842 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1843                                                   const DataLayout &DL) const {
1844   if (Subtarget->is64Bit()) {
1845     // Max of 8 and alignment of type.
1846     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1847     if (TyAlign > 8)
1848       return TyAlign;
1849     return 8;
1850   }
1851
1852   unsigned Align = 4;
1853   if (Subtarget->hasSSE1())
1854     getMaxByValAlign(Ty, Align);
1855   return Align;
1856 }
1857
1858 /// Returns the target specific optimal type for load
1859 /// and store operations as a result of memset, memcpy, and memmove
1860 /// lowering. If DstAlign is zero that means it's safe to destination
1861 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1862 /// means there isn't a need to check it against alignment requirement,
1863 /// probably because the source does not need to be loaded. If 'IsMemset' is
1864 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1865 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1866 /// source is constant so it does not need to be loaded.
1867 /// It returns EVT::Other if the type should be determined using generic
1868 /// target-independent logic.
1869 EVT
1870 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1871                                        unsigned DstAlign, unsigned SrcAlign,
1872                                        bool IsMemset, bool ZeroMemset,
1873                                        bool MemcpyStrSrc,
1874                                        MachineFunction &MF) const {
1875   const Function *F = MF.getFunction();
1876   if ((!IsMemset || ZeroMemset) &&
1877       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1878     if (Size >= 16 &&
1879         (!Subtarget->isUnalignedMemUnder32Slow() ||
1880          ((DstAlign == 0 || DstAlign >= 16) &&
1881           (SrcAlign == 0 || SrcAlign >= 16)))) {
1882       if (Size >= 32) {
1883         // FIXME: Check if unaligned 32-byte accesses are slow.
1884         if (Subtarget->hasInt256())
1885           return MVT::v8i32;
1886         if (Subtarget->hasFp256())
1887           return MVT::v8f32;
1888       }
1889       if (Subtarget->hasSSE2())
1890         return MVT::v4i32;
1891       if (Subtarget->hasSSE1())
1892         return MVT::v4f32;
1893     } else if (!MemcpyStrSrc && Size >= 8 &&
1894                !Subtarget->is64Bit() &&
1895                Subtarget->hasSSE2()) {
1896       // Do not use f64 to lower memcpy if source is string constant. It's
1897       // better to use i32 to avoid the loads.
1898       return MVT::f64;
1899     }
1900   }
1901   // This is a compromise. If we reach here, unaligned accesses may be slow on
1902   // this target. However, creating smaller, aligned accesses could be even
1903   // slower and would certainly be a lot more code.
1904   if (Subtarget->is64Bit() && Size >= 8)
1905     return MVT::i64;
1906   return MVT::i32;
1907 }
1908
1909 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1910   if (VT == MVT::f32)
1911     return X86ScalarSSEf32;
1912   else if (VT == MVT::f64)
1913     return X86ScalarSSEf64;
1914   return true;
1915 }
1916
1917 bool
1918 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1919                                                   unsigned,
1920                                                   unsigned,
1921                                                   bool *Fast) const {
1922   if (Fast) {
1923     if (VT.getSizeInBits() == 256)
1924       *Fast = !Subtarget->isUnalignedMem32Slow();
1925     else
1926       *Fast = !Subtarget->isUnalignedMemUnder32Slow();
1927   }
1928   return true;
1929 }
1930
1931 /// Return the entry encoding for a jump table in the
1932 /// current function.  The returned value is a member of the
1933 /// MachineJumpTableInfo::JTEntryKind enum.
1934 unsigned X86TargetLowering::getJumpTableEncoding() const {
1935   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1936   // symbol.
1937   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1938       Subtarget->isPICStyleGOT())
1939     return MachineJumpTableInfo::EK_Custom32;
1940
1941   // Otherwise, use the normal jump table encoding heuristics.
1942   return TargetLowering::getJumpTableEncoding();
1943 }
1944
1945 bool X86TargetLowering::useSoftFloat() const {
1946   return Subtarget->useSoftFloat();
1947 }
1948
1949 const MCExpr *
1950 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1951                                              const MachineBasicBlock *MBB,
1952                                              unsigned uid,MCContext &Ctx) const{
1953   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1954          Subtarget->isPICStyleGOT());
1955   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1956   // entries.
1957   return MCSymbolRefExpr::create(MBB->getSymbol(),
1958                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1959 }
1960
1961 /// Returns relocation base for the given PIC jumptable.
1962 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1963                                                     SelectionDAG &DAG) const {
1964   if (!Subtarget->is64Bit())
1965     // This doesn't have SDLoc associated with it, but is not really the
1966     // same as a Register.
1967     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1968                        getPointerTy(DAG.getDataLayout()));
1969   return Table;
1970 }
1971
1972 /// This returns the relocation base for the given PIC jumptable,
1973 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1974 const MCExpr *X86TargetLowering::
1975 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1976                              MCContext &Ctx) const {
1977   // X86-64 uses RIP relative addressing based on the jump table label.
1978   if (Subtarget->isPICStyleRIPRel())
1979     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1980
1981   // Otherwise, the reference is relative to the PIC base.
1982   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1983 }
1984
1985 std::pair<const TargetRegisterClass *, uint8_t>
1986 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1987                                            MVT VT) const {
1988   const TargetRegisterClass *RRC = nullptr;
1989   uint8_t Cost = 1;
1990   switch (VT.SimpleTy) {
1991   default:
1992     return TargetLowering::findRepresentativeClass(TRI, VT);
1993   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1994     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1995     break;
1996   case MVT::x86mmx:
1997     RRC = &X86::VR64RegClass;
1998     break;
1999   case MVT::f32: case MVT::f64:
2000   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2001   case MVT::v4f32: case MVT::v2f64:
2002   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2003   case MVT::v4f64:
2004     RRC = &X86::VR128RegClass;
2005     break;
2006   }
2007   return std::make_pair(RRC, Cost);
2008 }
2009
2010 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2011                                                unsigned &Offset) const {
2012   if (!Subtarget->isTargetLinux())
2013     return false;
2014
2015   if (Subtarget->is64Bit()) {
2016     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2017     Offset = 0x28;
2018     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2019       AddressSpace = 256;
2020     else
2021       AddressSpace = 257;
2022   } else {
2023     // %gs:0x14 on i386
2024     Offset = 0x14;
2025     AddressSpace = 256;
2026   }
2027   return true;
2028 }
2029
2030 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2031                                             unsigned DestAS) const {
2032   assert(SrcAS != DestAS && "Expected different address spaces!");
2033
2034   return SrcAS < 256 && DestAS < 256;
2035 }
2036
2037 //===----------------------------------------------------------------------===//
2038 //               Return Value Calling Convention Implementation
2039 //===----------------------------------------------------------------------===//
2040
2041 #include "X86GenCallingConv.inc"
2042
2043 bool
2044 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2045                                   MachineFunction &MF, bool isVarArg,
2046                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2047                         LLVMContext &Context) const {
2048   SmallVector<CCValAssign, 16> RVLocs;
2049   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2050   return CCInfo.CheckReturn(Outs, RetCC_X86);
2051 }
2052
2053 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2054   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2055   return ScratchRegs;
2056 }
2057
2058 SDValue
2059 X86TargetLowering::LowerReturn(SDValue Chain,
2060                                CallingConv::ID CallConv, bool isVarArg,
2061                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2062                                const SmallVectorImpl<SDValue> &OutVals,
2063                                SDLoc dl, SelectionDAG &DAG) const {
2064   MachineFunction &MF = DAG.getMachineFunction();
2065   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2066
2067   SmallVector<CCValAssign, 16> RVLocs;
2068   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2069   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2070
2071   SDValue Flag;
2072   SmallVector<SDValue, 6> RetOps;
2073   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2074   // Operand #1 = Bytes To Pop
2075   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2076                    MVT::i16));
2077
2078   // Copy the result values into the output registers.
2079   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2080     CCValAssign &VA = RVLocs[i];
2081     assert(VA.isRegLoc() && "Can only return in registers!");
2082     SDValue ValToCopy = OutVals[i];
2083     EVT ValVT = ValToCopy.getValueType();
2084
2085     // Promote values to the appropriate types.
2086     if (VA.getLocInfo() == CCValAssign::SExt)
2087       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2088     else if (VA.getLocInfo() == CCValAssign::ZExt)
2089       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2090     else if (VA.getLocInfo() == CCValAssign::AExt) {
2091       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2092         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2093       else
2094         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2095     }
2096     else if (VA.getLocInfo() == CCValAssign::BCvt)
2097       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2098
2099     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2100            "Unexpected FP-extend for return value.");
2101
2102     // If this is x86-64, and we disabled SSE, we can't return FP values,
2103     // or SSE or MMX vectors.
2104     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2105          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2106           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2107       report_fatal_error("SSE register return with SSE disabled");
2108     }
2109     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2110     // llvm-gcc has never done it right and no one has noticed, so this
2111     // should be OK for now.
2112     if (ValVT == MVT::f64 &&
2113         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2114       report_fatal_error("SSE2 register return with SSE2 disabled");
2115
2116     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2117     // the RET instruction and handled by the FP Stackifier.
2118     if (VA.getLocReg() == X86::FP0 ||
2119         VA.getLocReg() == X86::FP1) {
2120       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2121       // change the value to the FP stack register class.
2122       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2123         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2124       RetOps.push_back(ValToCopy);
2125       // Don't emit a copytoreg.
2126       continue;
2127     }
2128
2129     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2130     // which is returned in RAX / RDX.
2131     if (Subtarget->is64Bit()) {
2132       if (ValVT == MVT::x86mmx) {
2133         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2134           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2135           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2136                                   ValToCopy);
2137           // If we don't have SSE2 available, convert to v4f32 so the generated
2138           // register is legal.
2139           if (!Subtarget->hasSSE2())
2140             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2141         }
2142       }
2143     }
2144
2145     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2146     Flag = Chain.getValue(1);
2147     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2148   }
2149
2150   // All x86 ABIs require that for returning structs by value we copy
2151   // the sret argument into %rax/%eax (depending on ABI) for the return.
2152   // We saved the argument into a virtual register in the entry block,
2153   // so now we copy the value out and into %rax/%eax.
2154   //
2155   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2156   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2157   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2158   // either case FuncInfo->setSRetReturnReg() will have been called.
2159   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2160     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2161                                      getPointerTy(MF.getDataLayout()));
2162
2163     unsigned RetValReg
2164         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2165           X86::RAX : X86::EAX;
2166     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2167     Flag = Chain.getValue(1);
2168
2169     // RAX/EAX now acts like a return value.
2170     RetOps.push_back(
2171         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2172   }
2173
2174   RetOps[0] = Chain;  // Update chain.
2175
2176   // Add the flag if we have it.
2177   if (Flag.getNode())
2178     RetOps.push_back(Flag);
2179
2180   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2181 }
2182
2183 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2184   if (N->getNumValues() != 1)
2185     return false;
2186   if (!N->hasNUsesOfValue(1, 0))
2187     return false;
2188
2189   SDValue TCChain = Chain;
2190   SDNode *Copy = *N->use_begin();
2191   if (Copy->getOpcode() == ISD::CopyToReg) {
2192     // If the copy has a glue operand, we conservatively assume it isn't safe to
2193     // perform a tail call.
2194     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2195       return false;
2196     TCChain = Copy->getOperand(0);
2197   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2198     return false;
2199
2200   bool HasRet = false;
2201   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2202        UI != UE; ++UI) {
2203     if (UI->getOpcode() != X86ISD::RET_FLAG)
2204       return false;
2205     // If we are returning more than one value, we can definitely
2206     // not make a tail call see PR19530
2207     if (UI->getNumOperands() > 4)
2208       return false;
2209     if (UI->getNumOperands() == 4 &&
2210         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2211       return false;
2212     HasRet = true;
2213   }
2214
2215   if (!HasRet)
2216     return false;
2217
2218   Chain = TCChain;
2219   return true;
2220 }
2221
2222 EVT
2223 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2224                                             ISD::NodeType ExtendKind) const {
2225   MVT ReturnMVT;
2226   // TODO: Is this also valid on 32-bit?
2227   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2228     ReturnMVT = MVT::i8;
2229   else
2230     ReturnMVT = MVT::i32;
2231
2232   EVT MinVT = getRegisterType(Context, ReturnMVT);
2233   return VT.bitsLT(MinVT) ? MinVT : VT;
2234 }
2235
2236 /// Lower the result values of a call into the
2237 /// appropriate copies out of appropriate physical registers.
2238 ///
2239 SDValue
2240 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2241                                    CallingConv::ID CallConv, bool isVarArg,
2242                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2243                                    SDLoc dl, SelectionDAG &DAG,
2244                                    SmallVectorImpl<SDValue> &InVals) const {
2245
2246   // Assign locations to each value returned by this call.
2247   SmallVector<CCValAssign, 16> RVLocs;
2248   bool Is64Bit = Subtarget->is64Bit();
2249   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2250                  *DAG.getContext());
2251   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2252
2253   // Copy all of the result registers out of their specified physreg.
2254   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2255     CCValAssign &VA = RVLocs[i];
2256     EVT CopyVT = VA.getLocVT();
2257
2258     // If this is x86-64, and we disabled SSE, we can't return FP values
2259     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2260         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2261       report_fatal_error("SSE register return with SSE disabled");
2262     }
2263
2264     // If we prefer to use the value in xmm registers, copy it out as f80 and
2265     // use a truncate to move it from fp stack reg to xmm reg.
2266     bool RoundAfterCopy = false;
2267     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2268         isScalarFPTypeInSSEReg(VA.getValVT())) {
2269       CopyVT = MVT::f80;
2270       RoundAfterCopy = (CopyVT != VA.getLocVT());
2271     }
2272
2273     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2274                                CopyVT, InFlag).getValue(1);
2275     SDValue Val = Chain.getValue(0);
2276
2277     if (RoundAfterCopy)
2278       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2279                         // This truncation won't change the value.
2280                         DAG.getIntPtrConstant(1, dl));
2281
2282     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2283       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2284
2285     InFlag = Chain.getValue(2);
2286     InVals.push_back(Val);
2287   }
2288
2289   return Chain;
2290 }
2291
2292 //===----------------------------------------------------------------------===//
2293 //                C & StdCall & Fast Calling Convention implementation
2294 //===----------------------------------------------------------------------===//
2295 //  StdCall calling convention seems to be standard for many Windows' API
2296 //  routines and around. It differs from C calling convention just a little:
2297 //  callee should clean up the stack, not caller. Symbols should be also
2298 //  decorated in some fancy way :) It doesn't support any vector arguments.
2299 //  For info on fast calling convention see Fast Calling Convention (tail call)
2300 //  implementation LowerX86_32FastCCCallTo.
2301
2302 /// CallIsStructReturn - Determines whether a call uses struct return
2303 /// semantics.
2304 enum StructReturnType {
2305   NotStructReturn,
2306   RegStructReturn,
2307   StackStructReturn
2308 };
2309 static StructReturnType
2310 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2311   if (Outs.empty())
2312     return NotStructReturn;
2313
2314   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2315   if (!Flags.isSRet())
2316     return NotStructReturn;
2317   if (Flags.isInReg())
2318     return RegStructReturn;
2319   return StackStructReturn;
2320 }
2321
2322 /// Determines whether a function uses struct return semantics.
2323 static StructReturnType
2324 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2325   if (Ins.empty())
2326     return NotStructReturn;
2327
2328   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2329   if (!Flags.isSRet())
2330     return NotStructReturn;
2331   if (Flags.isInReg())
2332     return RegStructReturn;
2333   return StackStructReturn;
2334 }
2335
2336 /// Make a copy of an aggregate at address specified by "Src" to address
2337 /// "Dst" with size and alignment information specified by the specific
2338 /// parameter attribute. The copy will be passed as a byval function parameter.
2339 static SDValue
2340 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2341                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2342                           SDLoc dl) {
2343   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2344
2345   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2346                        /*isVolatile*/false, /*AlwaysInline=*/true,
2347                        /*isTailCall*/false,
2348                        MachinePointerInfo(), MachinePointerInfo());
2349 }
2350
2351 /// Return true if the calling convention is one that
2352 /// supports tail call optimization.
2353 static bool IsTailCallConvention(CallingConv::ID CC) {
2354   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2355           CC == CallingConv::HiPE);
2356 }
2357
2358 /// \brief Return true if the calling convention is a C calling convention.
2359 static bool IsCCallConvention(CallingConv::ID CC) {
2360   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2361           CC == CallingConv::X86_64_SysV);
2362 }
2363
2364 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2365   auto Attr =
2366       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2367   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2368     return false;
2369
2370   CallSite CS(CI);
2371   CallingConv::ID CalleeCC = CS.getCallingConv();
2372   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2373     return false;
2374
2375   return true;
2376 }
2377
2378 /// Return true if the function is being made into
2379 /// a tailcall target by changing its ABI.
2380 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2381                                    bool GuaranteedTailCallOpt) {
2382   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2383 }
2384
2385 SDValue
2386 X86TargetLowering::LowerMemArgument(SDValue Chain,
2387                                     CallingConv::ID CallConv,
2388                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2389                                     SDLoc dl, SelectionDAG &DAG,
2390                                     const CCValAssign &VA,
2391                                     MachineFrameInfo *MFI,
2392                                     unsigned i) const {
2393   // Create the nodes corresponding to a load from this parameter slot.
2394   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2395   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2396       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2397   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2398   EVT ValVT;
2399
2400   // If value is passed by pointer we have address passed instead of the value
2401   // itself.
2402   bool ExtendedInMem = VA.isExtInLoc() &&
2403     VA.getValVT().getScalarType() == MVT::i1;
2404
2405   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2406     ValVT = VA.getLocVT();
2407   else
2408     ValVT = VA.getValVT();
2409
2410   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2411   // changed with more analysis.
2412   // In case of tail call optimization mark all arguments mutable. Since they
2413   // could be overwritten by lowering of arguments in case of a tail call.
2414   if (Flags.isByVal()) {
2415     unsigned Bytes = Flags.getByValSize();
2416     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2417     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2418     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2419   } else {
2420     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2421                                     VA.getLocMemOffset(), isImmutable);
2422     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2423     SDValue Val = DAG.getLoad(
2424         ValVT, dl, Chain, FIN,
2425         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2426         false, false, 0);
2427     return ExtendedInMem ?
2428       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2429   }
2430 }
2431
2432 // FIXME: Get this from tablegen.
2433 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2434                                                 const X86Subtarget *Subtarget) {
2435   assert(Subtarget->is64Bit());
2436
2437   if (Subtarget->isCallingConvWin64(CallConv)) {
2438     static const MCPhysReg GPR64ArgRegsWin64[] = {
2439       X86::RCX, X86::RDX, X86::R8,  X86::R9
2440     };
2441     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2442   }
2443
2444   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2445     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2446   };
2447   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2448 }
2449
2450 // FIXME: Get this from tablegen.
2451 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2452                                                 CallingConv::ID CallConv,
2453                                                 const X86Subtarget *Subtarget) {
2454   assert(Subtarget->is64Bit());
2455   if (Subtarget->isCallingConvWin64(CallConv)) {
2456     // The XMM registers which might contain var arg parameters are shadowed
2457     // in their paired GPR.  So we only need to save the GPR to their home
2458     // slots.
2459     // TODO: __vectorcall will change this.
2460     return None;
2461   }
2462
2463   const Function *Fn = MF.getFunction();
2464   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2465   bool isSoftFloat = Subtarget->useSoftFloat();
2466   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2467          "SSE register cannot be used when SSE is disabled!");
2468   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2469     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2470     // registers.
2471     return None;
2472
2473   static const MCPhysReg XMMArgRegs64Bit[] = {
2474     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2475     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2476   };
2477   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2478 }
2479
2480 SDValue
2481 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2482                                         CallingConv::ID CallConv,
2483                                         bool isVarArg,
2484                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2485                                         SDLoc dl,
2486                                         SelectionDAG &DAG,
2487                                         SmallVectorImpl<SDValue> &InVals)
2488                                           const {
2489   MachineFunction &MF = DAG.getMachineFunction();
2490   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2491   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2492
2493   const Function* Fn = MF.getFunction();
2494   if (Fn->hasExternalLinkage() &&
2495       Subtarget->isTargetCygMing() &&
2496       Fn->getName() == "main")
2497     FuncInfo->setForceFramePointer(true);
2498
2499   MachineFrameInfo *MFI = MF.getFrameInfo();
2500   bool Is64Bit = Subtarget->is64Bit();
2501   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2502
2503   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2504          "Var args not supported with calling convention fastcc, ghc or hipe");
2505
2506   // Assign locations to all of the incoming arguments.
2507   SmallVector<CCValAssign, 16> ArgLocs;
2508   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2509
2510   // Allocate shadow area for Win64
2511   if (IsWin64)
2512     CCInfo.AllocateStack(32, 8);
2513
2514   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2515
2516   unsigned LastVal = ~0U;
2517   SDValue ArgValue;
2518   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2519     CCValAssign &VA = ArgLocs[i];
2520     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2521     // places.
2522     assert(VA.getValNo() != LastVal &&
2523            "Don't support value assigned to multiple locs yet");
2524     (void)LastVal;
2525     LastVal = VA.getValNo();
2526
2527     if (VA.isRegLoc()) {
2528       EVT RegVT = VA.getLocVT();
2529       const TargetRegisterClass *RC;
2530       if (RegVT == MVT::i32)
2531         RC = &X86::GR32RegClass;
2532       else if (Is64Bit && RegVT == MVT::i64)
2533         RC = &X86::GR64RegClass;
2534       else if (RegVT == MVT::f32)
2535         RC = &X86::FR32RegClass;
2536       else if (RegVT == MVT::f64)
2537         RC = &X86::FR64RegClass;
2538       else if (RegVT.is512BitVector())
2539         RC = &X86::VR512RegClass;
2540       else if (RegVT.is256BitVector())
2541         RC = &X86::VR256RegClass;
2542       else if (RegVT.is128BitVector())
2543         RC = &X86::VR128RegClass;
2544       else if (RegVT == MVT::x86mmx)
2545         RC = &X86::VR64RegClass;
2546       else if (RegVT == MVT::i1)
2547         RC = &X86::VK1RegClass;
2548       else if (RegVT == MVT::v8i1)
2549         RC = &X86::VK8RegClass;
2550       else if (RegVT == MVT::v16i1)
2551         RC = &X86::VK16RegClass;
2552       else if (RegVT == MVT::v32i1)
2553         RC = &X86::VK32RegClass;
2554       else if (RegVT == MVT::v64i1)
2555         RC = &X86::VK64RegClass;
2556       else
2557         llvm_unreachable("Unknown argument type!");
2558
2559       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2560       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2561
2562       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2563       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2564       // right size.
2565       if (VA.getLocInfo() == CCValAssign::SExt)
2566         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2567                                DAG.getValueType(VA.getValVT()));
2568       else if (VA.getLocInfo() == CCValAssign::ZExt)
2569         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2570                                DAG.getValueType(VA.getValVT()));
2571       else if (VA.getLocInfo() == CCValAssign::BCvt)
2572         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2573
2574       if (VA.isExtInLoc()) {
2575         // Handle MMX values passed in XMM regs.
2576         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2577           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2578         else
2579           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2580       }
2581     } else {
2582       assert(VA.isMemLoc());
2583       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2584     }
2585
2586     // If value is passed via pointer - do a load.
2587     if (VA.getLocInfo() == CCValAssign::Indirect)
2588       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2589                              MachinePointerInfo(), false, false, false, 0);
2590
2591     InVals.push_back(ArgValue);
2592   }
2593
2594   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2595     // All x86 ABIs require that for returning structs by value we copy the
2596     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2597     // the argument into a virtual register so that we can access it from the
2598     // return points.
2599     if (Ins[i].Flags.isSRet()) {
2600       unsigned Reg = FuncInfo->getSRetReturnReg();
2601       if (!Reg) {
2602         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2603         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2604         FuncInfo->setSRetReturnReg(Reg);
2605       }
2606       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2607       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2608       break;
2609     }
2610   }
2611
2612   unsigned StackSize = CCInfo.getNextStackOffset();
2613   // Align stack specially for tail calls.
2614   if (FuncIsMadeTailCallSafe(CallConv,
2615                              MF.getTarget().Options.GuaranteedTailCallOpt))
2616     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2617
2618   // If the function takes variable number of arguments, make a frame index for
2619   // the start of the first vararg value... for expansion of llvm.va_start. We
2620   // can skip this if there are no va_start calls.
2621   if (MFI->hasVAStart() &&
2622       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2623                    CallConv != CallingConv::X86_ThisCall))) {
2624     FuncInfo->setVarArgsFrameIndex(
2625         MFI->CreateFixedObject(1, StackSize, true));
2626   }
2627
2628   MachineModuleInfo &MMI = MF.getMMI();
2629   const Function *WinEHParent = nullptr;
2630   if (MMI.hasWinEHFuncInfo(Fn))
2631     WinEHParent = MMI.getWinEHParent(Fn);
2632   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2633   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2634
2635   // Figure out if XMM registers are in use.
2636   assert(!(Subtarget->useSoftFloat() &&
2637            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2638          "SSE register cannot be used when SSE is disabled!");
2639
2640   // 64-bit calling conventions support varargs and register parameters, so we
2641   // have to do extra work to spill them in the prologue.
2642   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2643     // Find the first unallocated argument registers.
2644     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2645     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2646     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2647     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2648     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2649            "SSE register cannot be used when SSE is disabled!");
2650
2651     // Gather all the live in physical registers.
2652     SmallVector<SDValue, 6> LiveGPRs;
2653     SmallVector<SDValue, 8> LiveXMMRegs;
2654     SDValue ALVal;
2655     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2656       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2657       LiveGPRs.push_back(
2658           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2659     }
2660     if (!ArgXMMs.empty()) {
2661       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2662       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2663       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2664         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2665         LiveXMMRegs.push_back(
2666             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2667       }
2668     }
2669
2670     if (IsWin64) {
2671       // Get to the caller-allocated home save location.  Add 8 to account
2672       // for the return address.
2673       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2674       FuncInfo->setRegSaveFrameIndex(
2675           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2676       // Fixup to set vararg frame on shadow area (4 x i64).
2677       if (NumIntRegs < 4)
2678         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2679     } else {
2680       // For X86-64, if there are vararg parameters that are passed via
2681       // registers, then we must store them to their spots on the stack so
2682       // they may be loaded by deferencing the result of va_next.
2683       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2684       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2685       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2686           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2687     }
2688
2689     // Store the integer parameter registers.
2690     SmallVector<SDValue, 8> MemOps;
2691     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2692                                       getPointerTy(DAG.getDataLayout()));
2693     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2694     for (SDValue Val : LiveGPRs) {
2695       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2696                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2697       SDValue Store =
2698           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2699                        MachinePointerInfo::getFixedStack(
2700                            DAG.getMachineFunction(),
2701                            FuncInfo->getRegSaveFrameIndex(), Offset),
2702                        false, false, 0);
2703       MemOps.push_back(Store);
2704       Offset += 8;
2705     }
2706
2707     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2708       // Now store the XMM (fp + vector) parameter registers.
2709       SmallVector<SDValue, 12> SaveXMMOps;
2710       SaveXMMOps.push_back(Chain);
2711       SaveXMMOps.push_back(ALVal);
2712       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2713                              FuncInfo->getRegSaveFrameIndex(), dl));
2714       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2715                              FuncInfo->getVarArgsFPOffset(), dl));
2716       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2717                         LiveXMMRegs.end());
2718       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2719                                    MVT::Other, SaveXMMOps));
2720     }
2721
2722     if (!MemOps.empty())
2723       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2724   } else if (IsWin64 && IsWinEHOutlined) {
2725     // Get to the caller-allocated home save location.  Add 8 to account
2726     // for the return address.
2727     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2728     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2729         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2730
2731     MMI.getWinEHFuncInfo(Fn)
2732         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2733         FuncInfo->getRegSaveFrameIndex();
2734
2735     // Store the second integer parameter (rdx) into rsp+16 relative to the
2736     // stack pointer at the entry of the function.
2737     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2738                                       getPointerTy(DAG.getDataLayout()));
2739     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2740     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2741     Chain = DAG.getStore(
2742         Val.getValue(1), dl, Val, RSFIN,
2743         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2744                                           FuncInfo->getRegSaveFrameIndex()),
2745         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2746   }
2747
2748   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2749     // Find the largest legal vector type.
2750     MVT VecVT = MVT::Other;
2751     // FIXME: Only some x86_32 calling conventions support AVX512.
2752     if (Subtarget->hasAVX512() &&
2753         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2754                      CallConv == CallingConv::Intel_OCL_BI)))
2755       VecVT = MVT::v16f32;
2756     else if (Subtarget->hasAVX())
2757       VecVT = MVT::v8f32;
2758     else if (Subtarget->hasSSE2())
2759       VecVT = MVT::v4f32;
2760
2761     // We forward some GPRs and some vector types.
2762     SmallVector<MVT, 2> RegParmTypes;
2763     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2764     RegParmTypes.push_back(IntVT);
2765     if (VecVT != MVT::Other)
2766       RegParmTypes.push_back(VecVT);
2767
2768     // Compute the set of forwarded registers. The rest are scratch.
2769     SmallVectorImpl<ForwardedRegister> &Forwards =
2770         FuncInfo->getForwardedMustTailRegParms();
2771     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2772
2773     // Conservatively forward AL on x86_64, since it might be used for varargs.
2774     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2775       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2776       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2777     }
2778
2779     // Copy all forwards from physical to virtual registers.
2780     for (ForwardedRegister &F : Forwards) {
2781       // FIXME: Can we use a less constrained schedule?
2782       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2783       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2784       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2785     }
2786   }
2787
2788   // Some CCs need callee pop.
2789   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2790                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2791     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2792   } else {
2793     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2794     // If this is an sret function, the return should pop the hidden pointer.
2795     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2796         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2797         argsAreStructReturn(Ins) == StackStructReturn)
2798       FuncInfo->setBytesToPopOnReturn(4);
2799   }
2800
2801   if (!Is64Bit) {
2802     // RegSaveFrameIndex is X86-64 only.
2803     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2804     if (CallConv == CallingConv::X86_FastCall ||
2805         CallConv == CallingConv::X86_ThisCall)
2806       // fastcc functions can't have varargs.
2807       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2808   }
2809
2810   FuncInfo->setArgumentStackSize(StackSize);
2811
2812   if (IsWinEHParent) {
2813     if (Is64Bit) {
2814       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2815       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2816       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2817       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2818       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2819                            MachinePointerInfo::getFixedStack(
2820                                DAG.getMachineFunction(), UnwindHelpFI),
2821                            /*isVolatile=*/true,
2822                            /*isNonTemporal=*/false, /*Alignment=*/0);
2823     } else {
2824       // Functions using Win32 EH are considered to have opaque SP adjustments
2825       // to force local variables to be addressed from the frame or base
2826       // pointers.
2827       MFI->setHasOpaqueSPAdjustment(true);
2828     }
2829   }
2830
2831   return Chain;
2832 }
2833
2834 SDValue
2835 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2836                                     SDValue StackPtr, SDValue Arg,
2837                                     SDLoc dl, SelectionDAG &DAG,
2838                                     const CCValAssign &VA,
2839                                     ISD::ArgFlagsTy Flags) const {
2840   unsigned LocMemOffset = VA.getLocMemOffset();
2841   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2842   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2843                        StackPtr, PtrOff);
2844   if (Flags.isByVal())
2845     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2846
2847   return DAG.getStore(
2848       Chain, dl, Arg, PtrOff,
2849       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2850       false, false, 0);
2851 }
2852
2853 /// Emit a load of return address if tail call
2854 /// optimization is performed and it is required.
2855 SDValue
2856 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2857                                            SDValue &OutRetAddr, SDValue Chain,
2858                                            bool IsTailCall, bool Is64Bit,
2859                                            int FPDiff, SDLoc dl) const {
2860   // Adjust the Return address stack slot.
2861   EVT VT = getPointerTy(DAG.getDataLayout());
2862   OutRetAddr = getReturnAddressFrameIndex(DAG);
2863
2864   // Load the "old" Return address.
2865   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2866                            false, false, false, 0);
2867   return SDValue(OutRetAddr.getNode(), 1);
2868 }
2869
2870 /// Emit a store of the return address if tail call
2871 /// optimization is performed and it is required (FPDiff!=0).
2872 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2873                                         SDValue Chain, SDValue RetAddrFrIdx,
2874                                         EVT PtrVT, unsigned SlotSize,
2875                                         int FPDiff, SDLoc dl) {
2876   // Store the return address to the appropriate stack slot.
2877   if (!FPDiff) return Chain;
2878   // Calculate the new stack slot for the return address.
2879   int NewReturnAddrFI =
2880     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2881                                          false);
2882   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2883   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2884                        MachinePointerInfo::getFixedStack(
2885                            DAG.getMachineFunction(), NewReturnAddrFI),
2886                        false, false, 0);
2887   return Chain;
2888 }
2889
2890 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2891 /// operation of specified width.
2892 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2893                        SDValue V2) {
2894   unsigned NumElems = VT.getVectorNumElements();
2895   SmallVector<int, 8> Mask;
2896   Mask.push_back(NumElems);
2897   for (unsigned i = 1; i != NumElems; ++i)
2898     Mask.push_back(i);
2899   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2900 }
2901
2902 SDValue
2903 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2904                              SmallVectorImpl<SDValue> &InVals) const {
2905   SelectionDAG &DAG                     = CLI.DAG;
2906   SDLoc &dl                             = CLI.DL;
2907   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2908   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2909   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2910   SDValue Chain                         = CLI.Chain;
2911   SDValue Callee                        = CLI.Callee;
2912   CallingConv::ID CallConv              = CLI.CallConv;
2913   bool &isTailCall                      = CLI.IsTailCall;
2914   bool isVarArg                         = CLI.IsVarArg;
2915
2916   MachineFunction &MF = DAG.getMachineFunction();
2917   bool Is64Bit        = Subtarget->is64Bit();
2918   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2919   StructReturnType SR = callIsStructReturn(Outs);
2920   bool IsSibcall      = false;
2921   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2922   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2923
2924   if (Attr.getValueAsString() == "true")
2925     isTailCall = false;
2926
2927   if (Subtarget->isPICStyleGOT() &&
2928       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2929     // If we are using a GOT, disable tail calls to external symbols with
2930     // default visibility. Tail calling such a symbol requires using a GOT
2931     // relocation, which forces early binding of the symbol. This breaks code
2932     // that require lazy function symbol resolution. Using musttail or
2933     // GuaranteedTailCallOpt will override this.
2934     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2935     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2936                G->getGlobal()->hasDefaultVisibility()))
2937       isTailCall = false;
2938   }
2939
2940   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2941   if (IsMustTail) {
2942     // Force this to be a tail call.  The verifier rules are enough to ensure
2943     // that we can lower this successfully without moving the return address
2944     // around.
2945     isTailCall = true;
2946   } else if (isTailCall) {
2947     // Check if it's really possible to do a tail call.
2948     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2949                     isVarArg, SR != NotStructReturn,
2950                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2951                     Outs, OutVals, Ins, DAG);
2952
2953     // Sibcalls are automatically detected tailcalls which do not require
2954     // ABI changes.
2955     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2956       IsSibcall = true;
2957
2958     if (isTailCall)
2959       ++NumTailCalls;
2960   }
2961
2962   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2963          "Var args not supported with calling convention fastcc, ghc or hipe");
2964
2965   // Analyze operands of the call, assigning locations to each operand.
2966   SmallVector<CCValAssign, 16> ArgLocs;
2967   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2968
2969   // Allocate shadow area for Win64
2970   if (IsWin64)
2971     CCInfo.AllocateStack(32, 8);
2972
2973   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2974
2975   // Get a count of how many bytes are to be pushed on the stack.
2976   unsigned NumBytes = CCInfo.getNextStackOffset();
2977   if (IsSibcall)
2978     // This is a sibcall. The memory operands are available in caller's
2979     // own caller's stack.
2980     NumBytes = 0;
2981   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2982            IsTailCallConvention(CallConv))
2983     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2984
2985   int FPDiff = 0;
2986   if (isTailCall && !IsSibcall && !IsMustTail) {
2987     // Lower arguments at fp - stackoffset + fpdiff.
2988     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2989
2990     FPDiff = NumBytesCallerPushed - NumBytes;
2991
2992     // Set the delta of movement of the returnaddr stackslot.
2993     // But only set if delta is greater than previous delta.
2994     if (FPDiff < X86Info->getTCReturnAddrDelta())
2995       X86Info->setTCReturnAddrDelta(FPDiff);
2996   }
2997
2998   unsigned NumBytesToPush = NumBytes;
2999   unsigned NumBytesToPop = NumBytes;
3000
3001   // If we have an inalloca argument, all stack space has already been allocated
3002   // for us and be right at the top of the stack.  We don't support multiple
3003   // arguments passed in memory when using inalloca.
3004   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3005     NumBytesToPush = 0;
3006     if (!ArgLocs.back().isMemLoc())
3007       report_fatal_error("cannot use inalloca attribute on a register "
3008                          "parameter");
3009     if (ArgLocs.back().getLocMemOffset() != 0)
3010       report_fatal_error("any parameter with the inalloca attribute must be "
3011                          "the only memory argument");
3012   }
3013
3014   if (!IsSibcall)
3015     Chain = DAG.getCALLSEQ_START(
3016         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3017
3018   SDValue RetAddrFrIdx;
3019   // Load return address for tail calls.
3020   if (isTailCall && FPDiff)
3021     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3022                                     Is64Bit, FPDiff, dl);
3023
3024   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3025   SmallVector<SDValue, 8> MemOpChains;
3026   SDValue StackPtr;
3027
3028   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3029   // of tail call optimization arguments are handle later.
3030   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3031   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3032     // Skip inalloca arguments, they have already been written.
3033     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3034     if (Flags.isInAlloca())
3035       continue;
3036
3037     CCValAssign &VA = ArgLocs[i];
3038     EVT RegVT = VA.getLocVT();
3039     SDValue Arg = OutVals[i];
3040     bool isByVal = Flags.isByVal();
3041
3042     // Promote the value if needed.
3043     switch (VA.getLocInfo()) {
3044     default: llvm_unreachable("Unknown loc info!");
3045     case CCValAssign::Full: break;
3046     case CCValAssign::SExt:
3047       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3048       break;
3049     case CCValAssign::ZExt:
3050       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3051       break;
3052     case CCValAssign::AExt:
3053       if (Arg.getValueType().isVector() &&
3054           Arg.getValueType().getScalarType() == MVT::i1)
3055         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3056       else if (RegVT.is128BitVector()) {
3057         // Special case: passing MMX values in XMM registers.
3058         Arg = DAG.getBitcast(MVT::i64, Arg);
3059         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3060         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3061       } else
3062         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3063       break;
3064     case CCValAssign::BCvt:
3065       Arg = DAG.getBitcast(RegVT, Arg);
3066       break;
3067     case CCValAssign::Indirect: {
3068       // Store the argument.
3069       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3070       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3071       Chain = DAG.getStore(
3072           Chain, dl, Arg, SpillSlot,
3073           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3074           false, false, 0);
3075       Arg = SpillSlot;
3076       break;
3077     }
3078     }
3079
3080     if (VA.isRegLoc()) {
3081       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3082       if (isVarArg && IsWin64) {
3083         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3084         // shadow reg if callee is a varargs function.
3085         unsigned ShadowReg = 0;
3086         switch (VA.getLocReg()) {
3087         case X86::XMM0: ShadowReg = X86::RCX; break;
3088         case X86::XMM1: ShadowReg = X86::RDX; break;
3089         case X86::XMM2: ShadowReg = X86::R8; break;
3090         case X86::XMM3: ShadowReg = X86::R9; break;
3091         }
3092         if (ShadowReg)
3093           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3094       }
3095     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3096       assert(VA.isMemLoc());
3097       if (!StackPtr.getNode())
3098         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3099                                       getPointerTy(DAG.getDataLayout()));
3100       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3101                                              dl, DAG, VA, Flags));
3102     }
3103   }
3104
3105   if (!MemOpChains.empty())
3106     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3107
3108   if (Subtarget->isPICStyleGOT()) {
3109     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3110     // GOT pointer.
3111     if (!isTailCall) {
3112       RegsToPass.push_back(std::make_pair(
3113           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3114                                           getPointerTy(DAG.getDataLayout()))));
3115     } else {
3116       // If we are tail calling and generating PIC/GOT style code load the
3117       // address of the callee into ECX. The value in ecx is used as target of
3118       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3119       // for tail calls on PIC/GOT architectures. Normally we would just put the
3120       // address of GOT into ebx and then call target@PLT. But for tail calls
3121       // ebx would be restored (since ebx is callee saved) before jumping to the
3122       // target@PLT.
3123
3124       // Note: The actual moving to ECX is done further down.
3125       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3126       if (G && !G->getGlobal()->hasLocalLinkage() &&
3127           G->getGlobal()->hasDefaultVisibility())
3128         Callee = LowerGlobalAddress(Callee, DAG);
3129       else if (isa<ExternalSymbolSDNode>(Callee))
3130         Callee = LowerExternalSymbol(Callee, DAG);
3131     }
3132   }
3133
3134   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3135     // From AMD64 ABI document:
3136     // For calls that may call functions that use varargs or stdargs
3137     // (prototype-less calls or calls to functions containing ellipsis (...) in
3138     // the declaration) %al is used as hidden argument to specify the number
3139     // of SSE registers used. The contents of %al do not need to match exactly
3140     // the number of registers, but must be an ubound on the number of SSE
3141     // registers used and is in the range 0 - 8 inclusive.
3142
3143     // Count the number of XMM registers allocated.
3144     static const MCPhysReg XMMArgRegs[] = {
3145       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3146       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3147     };
3148     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3149     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3150            && "SSE registers cannot be used when SSE is disabled");
3151
3152     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3153                                         DAG.getConstant(NumXMMRegs, dl,
3154                                                         MVT::i8)));
3155   }
3156
3157   if (isVarArg && IsMustTail) {
3158     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3159     for (const auto &F : Forwards) {
3160       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3161       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3162     }
3163   }
3164
3165   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3166   // don't need this because the eligibility check rejects calls that require
3167   // shuffling arguments passed in memory.
3168   if (!IsSibcall && isTailCall) {
3169     // Force all the incoming stack arguments to be loaded from the stack
3170     // before any new outgoing arguments are stored to the stack, because the
3171     // outgoing stack slots may alias the incoming argument stack slots, and
3172     // the alias isn't otherwise explicit. This is slightly more conservative
3173     // than necessary, because it means that each store effectively depends
3174     // on every argument instead of just those arguments it would clobber.
3175     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3176
3177     SmallVector<SDValue, 8> MemOpChains2;
3178     SDValue FIN;
3179     int FI = 0;
3180     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3181       CCValAssign &VA = ArgLocs[i];
3182       if (VA.isRegLoc())
3183         continue;
3184       assert(VA.isMemLoc());
3185       SDValue Arg = OutVals[i];
3186       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3187       // Skip inalloca arguments.  They don't require any work.
3188       if (Flags.isInAlloca())
3189         continue;
3190       // Create frame index.
3191       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3192       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3193       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3194       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3195
3196       if (Flags.isByVal()) {
3197         // Copy relative to framepointer.
3198         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3199         if (!StackPtr.getNode())
3200           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3201                                         getPointerTy(DAG.getDataLayout()));
3202         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3203                              StackPtr, Source);
3204
3205         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3206                                                          ArgChain,
3207                                                          Flags, DAG, dl));
3208       } else {
3209         // Store relative to framepointer.
3210         MemOpChains2.push_back(DAG.getStore(
3211             ArgChain, dl, Arg, FIN,
3212             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3213             false, false, 0));
3214       }
3215     }
3216
3217     if (!MemOpChains2.empty())
3218       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3219
3220     // Store the return address to the appropriate stack slot.
3221     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3222                                      getPointerTy(DAG.getDataLayout()),
3223                                      RegInfo->getSlotSize(), FPDiff, dl);
3224   }
3225
3226   // Build a sequence of copy-to-reg nodes chained together with token chain
3227   // and flag operands which copy the outgoing args into registers.
3228   SDValue InFlag;
3229   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3230     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3231                              RegsToPass[i].second, InFlag);
3232     InFlag = Chain.getValue(1);
3233   }
3234
3235   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3236     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3237     // In the 64-bit large code model, we have to make all calls
3238     // through a register, since the call instruction's 32-bit
3239     // pc-relative offset may not be large enough to hold the whole
3240     // address.
3241   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3242     // If the callee is a GlobalAddress node (quite common, every direct call
3243     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3244     // it.
3245     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3246
3247     // We should use extra load for direct calls to dllimported functions in
3248     // non-JIT mode.
3249     const GlobalValue *GV = G->getGlobal();
3250     if (!GV->hasDLLImportStorageClass()) {
3251       unsigned char OpFlags = 0;
3252       bool ExtraLoad = false;
3253       unsigned WrapperKind = ISD::DELETED_NODE;
3254
3255       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3256       // external symbols most go through the PLT in PIC mode.  If the symbol
3257       // has hidden or protected visibility, or if it is static or local, then
3258       // we don't need to use the PLT - we can directly call it.
3259       if (Subtarget->isTargetELF() &&
3260           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3261           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3262         OpFlags = X86II::MO_PLT;
3263       } else if (Subtarget->isPICStyleStubAny() &&
3264                  !GV->isStrongDefinitionForLinker() &&
3265                  (!Subtarget->getTargetTriple().isMacOSX() ||
3266                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3267         // PC-relative references to external symbols should go through $stub,
3268         // unless we're building with the leopard linker or later, which
3269         // automatically synthesizes these stubs.
3270         OpFlags = X86II::MO_DARWIN_STUB;
3271       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3272                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3273         // If the function is marked as non-lazy, generate an indirect call
3274         // which loads from the GOT directly. This avoids runtime overhead
3275         // at the cost of eager binding (and one extra byte of encoding).
3276         OpFlags = X86II::MO_GOTPCREL;
3277         WrapperKind = X86ISD::WrapperRIP;
3278         ExtraLoad = true;
3279       }
3280
3281       Callee = DAG.getTargetGlobalAddress(
3282           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3283
3284       // Add a wrapper if needed.
3285       if (WrapperKind != ISD::DELETED_NODE)
3286         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3287                              getPointerTy(DAG.getDataLayout()), Callee);
3288       // Add extra indirection if needed.
3289       if (ExtraLoad)
3290         Callee = DAG.getLoad(
3291             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3292             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3293             false, 0);
3294     }
3295   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3296     unsigned char OpFlags = 0;
3297
3298     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3299     // external symbols should go through the PLT.
3300     if (Subtarget->isTargetELF() &&
3301         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3302       OpFlags = X86II::MO_PLT;
3303     } else if (Subtarget->isPICStyleStubAny() &&
3304                (!Subtarget->getTargetTriple().isMacOSX() ||
3305                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3306       // PC-relative references to external symbols should go through $stub,
3307       // unless we're building with the leopard linker or later, which
3308       // automatically synthesizes these stubs.
3309       OpFlags = X86II::MO_DARWIN_STUB;
3310     }
3311
3312     Callee = DAG.getTargetExternalSymbol(
3313         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3314   } else if (Subtarget->isTarget64BitILP32() &&
3315              Callee->getValueType(0) == MVT::i32) {
3316     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3317     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3318   }
3319
3320   // Returns a chain & a flag for retval copy to use.
3321   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3322   SmallVector<SDValue, 8> Ops;
3323
3324   if (!IsSibcall && isTailCall) {
3325     Chain = DAG.getCALLSEQ_END(Chain,
3326                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3327                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3328     InFlag = Chain.getValue(1);
3329   }
3330
3331   Ops.push_back(Chain);
3332   Ops.push_back(Callee);
3333
3334   if (isTailCall)
3335     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3336
3337   // Add argument registers to the end of the list so that they are known live
3338   // into the call.
3339   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3340     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3341                                   RegsToPass[i].second.getValueType()));
3342
3343   // Add a register mask operand representing the call-preserved registers.
3344   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3345   assert(Mask && "Missing call preserved mask for calling convention");
3346
3347   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3348   // the function clobbers all registers. If an exception is thrown, the runtime
3349   // will not restore CSRs.
3350   // FIXME: Model this more precisely so that we can register allocate across
3351   // the normal edge and spill and fill across the exceptional edge.
3352   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3353     const Function *CallerFn = MF.getFunction();
3354     EHPersonality Pers =
3355         CallerFn->hasPersonalityFn()
3356             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3357             : EHPersonality::Unknown;
3358     if (isMSVCEHPersonality(Pers))
3359       Mask = RegInfo->getNoPreservedMask();
3360   }
3361
3362   Ops.push_back(DAG.getRegisterMask(Mask));
3363
3364   if (InFlag.getNode())
3365     Ops.push_back(InFlag);
3366
3367   if (isTailCall) {
3368     // We used to do:
3369     //// If this is the first return lowered for this function, add the regs
3370     //// to the liveout set for the function.
3371     // This isn't right, although it's probably harmless on x86; liveouts
3372     // should be computed from returns not tail calls.  Consider a void
3373     // function making a tail call to a function returning int.
3374     MF.getFrameInfo()->setHasTailCall();
3375     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3376   }
3377
3378   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3379   InFlag = Chain.getValue(1);
3380
3381   // Create the CALLSEQ_END node.
3382   unsigned NumBytesForCalleeToPop;
3383   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3384                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3385     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3386   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3387            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3388            SR == StackStructReturn)
3389     // If this is a call to a struct-return function, the callee
3390     // pops the hidden struct pointer, so we have to push it back.
3391     // This is common for Darwin/X86, Linux & Mingw32 targets.
3392     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3393     NumBytesForCalleeToPop = 4;
3394   else
3395     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3396
3397   // Returns a flag for retval copy to use.
3398   if (!IsSibcall) {
3399     Chain = DAG.getCALLSEQ_END(Chain,
3400                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3401                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3402                                                      true),
3403                                InFlag, dl);
3404     InFlag = Chain.getValue(1);
3405   }
3406
3407   // Handle result values, copying them out of physregs into vregs that we
3408   // return.
3409   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3410                          Ins, dl, DAG, InVals);
3411 }
3412
3413 //===----------------------------------------------------------------------===//
3414 //                Fast Calling Convention (tail call) implementation
3415 //===----------------------------------------------------------------------===//
3416
3417 //  Like std call, callee cleans arguments, convention except that ECX is
3418 //  reserved for storing the tail called function address. Only 2 registers are
3419 //  free for argument passing (inreg). Tail call optimization is performed
3420 //  provided:
3421 //                * tailcallopt is enabled
3422 //                * caller/callee are fastcc
3423 //  On X86_64 architecture with GOT-style position independent code only local
3424 //  (within module) calls are supported at the moment.
3425 //  To keep the stack aligned according to platform abi the function
3426 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3427 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3428 //  If a tail called function callee has more arguments than the caller the
3429 //  caller needs to make sure that there is room to move the RETADDR to. This is
3430 //  achieved by reserving an area the size of the argument delta right after the
3431 //  original RETADDR, but before the saved framepointer or the spilled registers
3432 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3433 //  stack layout:
3434 //    arg1
3435 //    arg2
3436 //    RETADDR
3437 //    [ new RETADDR
3438 //      move area ]
3439 //    (possible EBP)
3440 //    ESI
3441 //    EDI
3442 //    local1 ..
3443
3444 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3445 /// requirement.
3446 unsigned
3447 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3448                                                SelectionDAG& DAG) const {
3449   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3450   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3451   unsigned StackAlignment = TFI.getStackAlignment();
3452   uint64_t AlignMask = StackAlignment - 1;
3453   int64_t Offset = StackSize;
3454   unsigned SlotSize = RegInfo->getSlotSize();
3455   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3456     // Number smaller than 12 so just add the difference.
3457     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3458   } else {
3459     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3460     Offset = ((~AlignMask) & Offset) + StackAlignment +
3461       (StackAlignment-SlotSize);
3462   }
3463   return Offset;
3464 }
3465
3466 /// Return true if the given stack call argument is already available in the
3467 /// same position (relatively) of the caller's incoming argument stack.
3468 static
3469 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3470                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3471                          const X86InstrInfo *TII) {
3472   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3473   int FI = INT_MAX;
3474   if (Arg.getOpcode() == ISD::CopyFromReg) {
3475     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3476     if (!TargetRegisterInfo::isVirtualRegister(VR))
3477       return false;
3478     MachineInstr *Def = MRI->getVRegDef(VR);
3479     if (!Def)
3480       return false;
3481     if (!Flags.isByVal()) {
3482       if (!TII->isLoadFromStackSlot(Def, FI))
3483         return false;
3484     } else {
3485       unsigned Opcode = Def->getOpcode();
3486       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3487            Opcode == X86::LEA64_32r) &&
3488           Def->getOperand(1).isFI()) {
3489         FI = Def->getOperand(1).getIndex();
3490         Bytes = Flags.getByValSize();
3491       } else
3492         return false;
3493     }
3494   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3495     if (Flags.isByVal())
3496       // ByVal argument is passed in as a pointer but it's now being
3497       // dereferenced. e.g.
3498       // define @foo(%struct.X* %A) {
3499       //   tail call @bar(%struct.X* byval %A)
3500       // }
3501       return false;
3502     SDValue Ptr = Ld->getBasePtr();
3503     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3504     if (!FINode)
3505       return false;
3506     FI = FINode->getIndex();
3507   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3508     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3509     FI = FINode->getIndex();
3510     Bytes = Flags.getByValSize();
3511   } else
3512     return false;
3513
3514   assert(FI != INT_MAX);
3515   if (!MFI->isFixedObjectIndex(FI))
3516     return false;
3517   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3518 }
3519
3520 /// Check whether the call is eligible for tail call optimization. Targets
3521 /// that want to do tail call optimization should implement this function.
3522 bool
3523 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3524                                                      CallingConv::ID CalleeCC,
3525                                                      bool isVarArg,
3526                                                      bool isCalleeStructRet,
3527                                                      bool isCallerStructRet,
3528                                                      Type *RetTy,
3529                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3530                                     const SmallVectorImpl<SDValue> &OutVals,
3531                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3532                                                      SelectionDAG &DAG) const {
3533   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3534     return false;
3535
3536   // If -tailcallopt is specified, make fastcc functions tail-callable.
3537   const MachineFunction &MF = DAG.getMachineFunction();
3538   const Function *CallerF = MF.getFunction();
3539
3540   // If the function return type is x86_fp80 and the callee return type is not,
3541   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3542   // perform a tailcall optimization here.
3543   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3544     return false;
3545
3546   CallingConv::ID CallerCC = CallerF->getCallingConv();
3547   bool CCMatch = CallerCC == CalleeCC;
3548   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3549   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3550
3551   // Win64 functions have extra shadow space for argument homing. Don't do the
3552   // sibcall if the caller and callee have mismatched expectations for this
3553   // space.
3554   if (IsCalleeWin64 != IsCallerWin64)
3555     return false;
3556
3557   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3558     if (IsTailCallConvention(CalleeCC) && CCMatch)
3559       return true;
3560     return false;
3561   }
3562
3563   // Look for obvious safe cases to perform tail call optimization that do not
3564   // require ABI changes. This is what gcc calls sibcall.
3565
3566   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3567   // emit a special epilogue.
3568   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3569   if (RegInfo->needsStackRealignment(MF))
3570     return false;
3571
3572   // Also avoid sibcall optimization if either caller or callee uses struct
3573   // return semantics.
3574   if (isCalleeStructRet || isCallerStructRet)
3575     return false;
3576
3577   // An stdcall/thiscall caller is expected to clean up its arguments; the
3578   // callee isn't going to do that.
3579   // FIXME: this is more restrictive than needed. We could produce a tailcall
3580   // when the stack adjustment matches. For example, with a thiscall that takes
3581   // only one argument.
3582   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3583                    CallerCC == CallingConv::X86_ThisCall))
3584     return false;
3585
3586   // Do not sibcall optimize vararg calls unless all arguments are passed via
3587   // registers.
3588   if (isVarArg && !Outs.empty()) {
3589
3590     // Optimizing for varargs on Win64 is unlikely to be safe without
3591     // additional testing.
3592     if (IsCalleeWin64 || IsCallerWin64)
3593       return false;
3594
3595     SmallVector<CCValAssign, 16> ArgLocs;
3596     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3597                    *DAG.getContext());
3598
3599     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3600     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3601       if (!ArgLocs[i].isRegLoc())
3602         return false;
3603   }
3604
3605   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3606   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3607   // this into a sibcall.
3608   bool Unused = false;
3609   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3610     if (!Ins[i].Used) {
3611       Unused = true;
3612       break;
3613     }
3614   }
3615   if (Unused) {
3616     SmallVector<CCValAssign, 16> RVLocs;
3617     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3618                    *DAG.getContext());
3619     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3620     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3621       CCValAssign &VA = RVLocs[i];
3622       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3623         return false;
3624     }
3625   }
3626
3627   // If the calling conventions do not match, then we'd better make sure the
3628   // results are returned in the same way as what the caller expects.
3629   if (!CCMatch) {
3630     SmallVector<CCValAssign, 16> RVLocs1;
3631     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3632                     *DAG.getContext());
3633     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3634
3635     SmallVector<CCValAssign, 16> RVLocs2;
3636     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3637                     *DAG.getContext());
3638     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3639
3640     if (RVLocs1.size() != RVLocs2.size())
3641       return false;
3642     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3643       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3644         return false;
3645       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3646         return false;
3647       if (RVLocs1[i].isRegLoc()) {
3648         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3649           return false;
3650       } else {
3651         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3652           return false;
3653       }
3654     }
3655   }
3656
3657   // If the callee takes no arguments then go on to check the results of the
3658   // call.
3659   if (!Outs.empty()) {
3660     // Check if stack adjustment is needed. For now, do not do this if any
3661     // argument is passed on the stack.
3662     SmallVector<CCValAssign, 16> ArgLocs;
3663     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3664                    *DAG.getContext());
3665
3666     // Allocate shadow area for Win64
3667     if (IsCalleeWin64)
3668       CCInfo.AllocateStack(32, 8);
3669
3670     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3671     if (CCInfo.getNextStackOffset()) {
3672       MachineFunction &MF = DAG.getMachineFunction();
3673       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3674         return false;
3675
3676       // Check if the arguments are already laid out in the right way as
3677       // the caller's fixed stack objects.
3678       MachineFrameInfo *MFI = MF.getFrameInfo();
3679       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3680       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3681       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3682         CCValAssign &VA = ArgLocs[i];
3683         SDValue Arg = OutVals[i];
3684         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3685         if (VA.getLocInfo() == CCValAssign::Indirect)
3686           return false;
3687         if (!VA.isRegLoc()) {
3688           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3689                                    MFI, MRI, TII))
3690             return false;
3691         }
3692       }
3693     }
3694
3695     // If the tailcall address may be in a register, then make sure it's
3696     // possible to register allocate for it. In 32-bit, the call address can
3697     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3698     // callee-saved registers are restored. These happen to be the same
3699     // registers used to pass 'inreg' arguments so watch out for those.
3700     if (!Subtarget->is64Bit() &&
3701         ((!isa<GlobalAddressSDNode>(Callee) &&
3702           !isa<ExternalSymbolSDNode>(Callee)) ||
3703          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3704       unsigned NumInRegs = 0;
3705       // In PIC we need an extra register to formulate the address computation
3706       // for the callee.
3707       unsigned MaxInRegs =
3708         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3709
3710       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3711         CCValAssign &VA = ArgLocs[i];
3712         if (!VA.isRegLoc())
3713           continue;
3714         unsigned Reg = VA.getLocReg();
3715         switch (Reg) {
3716         default: break;
3717         case X86::EAX: case X86::EDX: case X86::ECX:
3718           if (++NumInRegs == MaxInRegs)
3719             return false;
3720           break;
3721         }
3722       }
3723     }
3724   }
3725
3726   return true;
3727 }
3728
3729 FastISel *
3730 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3731                                   const TargetLibraryInfo *libInfo) const {
3732   return X86::createFastISel(funcInfo, libInfo);
3733 }
3734
3735 //===----------------------------------------------------------------------===//
3736 //                           Other Lowering Hooks
3737 //===----------------------------------------------------------------------===//
3738
3739 static bool MayFoldLoad(SDValue Op) {
3740   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3741 }
3742
3743 static bool MayFoldIntoStore(SDValue Op) {
3744   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3745 }
3746
3747 static bool isTargetShuffle(unsigned Opcode) {
3748   switch(Opcode) {
3749   default: return false;
3750   case X86ISD::BLENDI:
3751   case X86ISD::PSHUFB:
3752   case X86ISD::PSHUFD:
3753   case X86ISD::PSHUFHW:
3754   case X86ISD::PSHUFLW:
3755   case X86ISD::SHUFP:
3756   case X86ISD::PALIGNR:
3757   case X86ISD::MOVLHPS:
3758   case X86ISD::MOVLHPD:
3759   case X86ISD::MOVHLPS:
3760   case X86ISD::MOVLPS:
3761   case X86ISD::MOVLPD:
3762   case X86ISD::MOVSHDUP:
3763   case X86ISD::MOVSLDUP:
3764   case X86ISD::MOVDDUP:
3765   case X86ISD::MOVSS:
3766   case X86ISD::MOVSD:
3767   case X86ISD::UNPCKL:
3768   case X86ISD::UNPCKH:
3769   case X86ISD::VPERMILPI:
3770   case X86ISD::VPERM2X128:
3771   case X86ISD::VPERMI:
3772     return true;
3773   }
3774 }
3775
3776 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3777                                     SDValue V1, unsigned TargetMask,
3778                                     SelectionDAG &DAG) {
3779   switch(Opc) {
3780   default: llvm_unreachable("Unknown x86 shuffle node");
3781   case X86ISD::PSHUFD:
3782   case X86ISD::PSHUFHW:
3783   case X86ISD::PSHUFLW:
3784   case X86ISD::VPERMILPI:
3785   case X86ISD::VPERMI:
3786     return DAG.getNode(Opc, dl, VT, V1,
3787                        DAG.getConstant(TargetMask, dl, MVT::i8));
3788   }
3789 }
3790
3791 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3792                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3793   switch(Opc) {
3794   default: llvm_unreachable("Unknown x86 shuffle node");
3795   case X86ISD::MOVLHPS:
3796   case X86ISD::MOVLHPD:
3797   case X86ISD::MOVHLPS:
3798   case X86ISD::MOVLPS:
3799   case X86ISD::MOVLPD:
3800   case X86ISD::MOVSS:
3801   case X86ISD::MOVSD:
3802   case X86ISD::UNPCKL:
3803   case X86ISD::UNPCKH:
3804     return DAG.getNode(Opc, dl, VT, V1, V2);
3805   }
3806 }
3807
3808 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3809   MachineFunction &MF = DAG.getMachineFunction();
3810   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3811   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3812   int ReturnAddrIndex = FuncInfo->getRAIndex();
3813
3814   if (ReturnAddrIndex == 0) {
3815     // Set up a frame object for the return address.
3816     unsigned SlotSize = RegInfo->getSlotSize();
3817     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3818                                                            -(int64_t)SlotSize,
3819                                                            false);
3820     FuncInfo->setRAIndex(ReturnAddrIndex);
3821   }
3822
3823   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3824 }
3825
3826 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3827                                        bool hasSymbolicDisplacement) {
3828   // Offset should fit into 32 bit immediate field.
3829   if (!isInt<32>(Offset))
3830     return false;
3831
3832   // If we don't have a symbolic displacement - we don't have any extra
3833   // restrictions.
3834   if (!hasSymbolicDisplacement)
3835     return true;
3836
3837   // FIXME: Some tweaks might be needed for medium code model.
3838   if (M != CodeModel::Small && M != CodeModel::Kernel)
3839     return false;
3840
3841   // For small code model we assume that latest object is 16MB before end of 31
3842   // bits boundary. We may also accept pretty large negative constants knowing
3843   // that all objects are in the positive half of address space.
3844   if (M == CodeModel::Small && Offset < 16*1024*1024)
3845     return true;
3846
3847   // For kernel code model we know that all object resist in the negative half
3848   // of 32bits address space. We may not accept negative offsets, since they may
3849   // be just off and we may accept pretty large positive ones.
3850   if (M == CodeModel::Kernel && Offset >= 0)
3851     return true;
3852
3853   return false;
3854 }
3855
3856 /// Determines whether the callee is required to pop its own arguments.
3857 /// Callee pop is necessary to support tail calls.
3858 bool X86::isCalleePop(CallingConv::ID CallingConv,
3859                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3860   switch (CallingConv) {
3861   default:
3862     return false;
3863   case CallingConv::X86_StdCall:
3864   case CallingConv::X86_FastCall:
3865   case CallingConv::X86_ThisCall:
3866     return !is64Bit;
3867   case CallingConv::Fast:
3868   case CallingConv::GHC:
3869   case CallingConv::HiPE:
3870     if (IsVarArg)
3871       return false;
3872     return TailCallOpt;
3873   }
3874 }
3875
3876 /// \brief Return true if the condition is an unsigned comparison operation.
3877 static bool isX86CCUnsigned(unsigned X86CC) {
3878   switch (X86CC) {
3879   default: llvm_unreachable("Invalid integer condition!");
3880   case X86::COND_E:     return true;
3881   case X86::COND_G:     return false;
3882   case X86::COND_GE:    return false;
3883   case X86::COND_L:     return false;
3884   case X86::COND_LE:    return false;
3885   case X86::COND_NE:    return true;
3886   case X86::COND_B:     return true;
3887   case X86::COND_A:     return true;
3888   case X86::COND_BE:    return true;
3889   case X86::COND_AE:    return true;
3890   }
3891   llvm_unreachable("covered switch fell through?!");
3892 }
3893
3894 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3895 /// condition code, returning the condition code and the LHS/RHS of the
3896 /// comparison to make.
3897 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3898                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3899   if (!isFP) {
3900     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3901       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3902         // X > -1   -> X == 0, jump !sign.
3903         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3904         return X86::COND_NS;
3905       }
3906       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3907         // X < 0   -> X == 0, jump on sign.
3908         return X86::COND_S;
3909       }
3910       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3911         // X < 1   -> X <= 0
3912         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3913         return X86::COND_LE;
3914       }
3915     }
3916
3917     switch (SetCCOpcode) {
3918     default: llvm_unreachable("Invalid integer condition!");
3919     case ISD::SETEQ:  return X86::COND_E;
3920     case ISD::SETGT:  return X86::COND_G;
3921     case ISD::SETGE:  return X86::COND_GE;
3922     case ISD::SETLT:  return X86::COND_L;
3923     case ISD::SETLE:  return X86::COND_LE;
3924     case ISD::SETNE:  return X86::COND_NE;
3925     case ISD::SETULT: return X86::COND_B;
3926     case ISD::SETUGT: return X86::COND_A;
3927     case ISD::SETULE: return X86::COND_BE;
3928     case ISD::SETUGE: return X86::COND_AE;
3929     }
3930   }
3931
3932   // First determine if it is required or is profitable to flip the operands.
3933
3934   // If LHS is a foldable load, but RHS is not, flip the condition.
3935   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3936       !ISD::isNON_EXTLoad(RHS.getNode())) {
3937     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3938     std::swap(LHS, RHS);
3939   }
3940
3941   switch (SetCCOpcode) {
3942   default: break;
3943   case ISD::SETOLT:
3944   case ISD::SETOLE:
3945   case ISD::SETUGT:
3946   case ISD::SETUGE:
3947     std::swap(LHS, RHS);
3948     break;
3949   }
3950
3951   // On a floating point condition, the flags are set as follows:
3952   // ZF  PF  CF   op
3953   //  0 | 0 | 0 | X > Y
3954   //  0 | 0 | 1 | X < Y
3955   //  1 | 0 | 0 | X == Y
3956   //  1 | 1 | 1 | unordered
3957   switch (SetCCOpcode) {
3958   default: llvm_unreachable("Condcode should be pre-legalized away");
3959   case ISD::SETUEQ:
3960   case ISD::SETEQ:   return X86::COND_E;
3961   case ISD::SETOLT:              // flipped
3962   case ISD::SETOGT:
3963   case ISD::SETGT:   return X86::COND_A;
3964   case ISD::SETOLE:              // flipped
3965   case ISD::SETOGE:
3966   case ISD::SETGE:   return X86::COND_AE;
3967   case ISD::SETUGT:              // flipped
3968   case ISD::SETULT:
3969   case ISD::SETLT:   return X86::COND_B;
3970   case ISD::SETUGE:              // flipped
3971   case ISD::SETULE:
3972   case ISD::SETLE:   return X86::COND_BE;
3973   case ISD::SETONE:
3974   case ISD::SETNE:   return X86::COND_NE;
3975   case ISD::SETUO:   return X86::COND_P;
3976   case ISD::SETO:    return X86::COND_NP;
3977   case ISD::SETOEQ:
3978   case ISD::SETUNE:  return X86::COND_INVALID;
3979   }
3980 }
3981
3982 /// Is there a floating point cmov for the specific X86 condition code?
3983 /// Current x86 isa includes the following FP cmov instructions:
3984 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3985 static bool hasFPCMov(unsigned X86CC) {
3986   switch (X86CC) {
3987   default:
3988     return false;
3989   case X86::COND_B:
3990   case X86::COND_BE:
3991   case X86::COND_E:
3992   case X86::COND_P:
3993   case X86::COND_A:
3994   case X86::COND_AE:
3995   case X86::COND_NE:
3996   case X86::COND_NP:
3997     return true;
3998   }
3999 }
4000
4001 /// Returns true if the target can instruction select the
4002 /// specified FP immediate natively. If false, the legalizer will
4003 /// materialize the FP immediate as a load from a constant pool.
4004 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4005   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4006     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4007       return true;
4008   }
4009   return false;
4010 }
4011
4012 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4013                                               ISD::LoadExtType ExtTy,
4014                                               EVT NewVT) const {
4015   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4016   // relocation target a movq or addq instruction: don't let the load shrink.
4017   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4018   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4019     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4020       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4021   return true;
4022 }
4023
4024 /// \brief Returns true if it is beneficial to convert a load of a constant
4025 /// to just the constant itself.
4026 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4027                                                           Type *Ty) const {
4028   assert(Ty->isIntegerTy());
4029
4030   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4031   if (BitSize == 0 || BitSize > 64)
4032     return false;
4033   return true;
4034 }
4035
4036 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4037                                                 unsigned Index) const {
4038   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4039     return false;
4040
4041   return (Index == 0 || Index == ResVT.getVectorNumElements());
4042 }
4043
4044 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4045   // Speculate cttz only if we can directly use TZCNT.
4046   return Subtarget->hasBMI();
4047 }
4048
4049 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4050   // Speculate ctlz only if we can directly use LZCNT.
4051   return Subtarget->hasLZCNT();
4052 }
4053
4054 /// Return true if every element in Mask, beginning
4055 /// from position Pos and ending in Pos+Size is undef.
4056 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4057   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4058     if (0 <= Mask[i])
4059       return false;
4060   return true;
4061 }
4062
4063 /// Return true if Val is undef or if its value falls within the
4064 /// specified range (L, H].
4065 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4066   return (Val < 0) || (Val >= Low && Val < Hi);
4067 }
4068
4069 /// Val is either less than zero (undef) or equal to the specified value.
4070 static bool isUndefOrEqual(int Val, int CmpVal) {
4071   return (Val < 0 || Val == CmpVal);
4072 }
4073
4074 /// Return true if every element in Mask, beginning
4075 /// from position Pos and ending in Pos+Size, falls within the specified
4076 /// sequential range (Low, Low+Size]. or is undef.
4077 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4078                                        unsigned Pos, unsigned Size, int Low) {
4079   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4080     if (!isUndefOrEqual(Mask[i], Low))
4081       return false;
4082   return true;
4083 }
4084
4085 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4086 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4087 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4088   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4089   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4090     return false;
4091
4092   // The index should be aligned on a vecWidth-bit boundary.
4093   uint64_t Index =
4094     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4095
4096   MVT VT = N->getSimpleValueType(0);
4097   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4098   bool Result = (Index * ElSize) % vecWidth == 0;
4099
4100   return Result;
4101 }
4102
4103 /// Return true if the specified INSERT_SUBVECTOR
4104 /// operand specifies a subvector insert that is suitable for input to
4105 /// insertion of 128 or 256-bit subvectors
4106 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4107   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4108   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4109     return false;
4110   // The index should be aligned on a vecWidth-bit boundary.
4111   uint64_t Index =
4112     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4113
4114   MVT VT = N->getSimpleValueType(0);
4115   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4116   bool Result = (Index * ElSize) % vecWidth == 0;
4117
4118   return Result;
4119 }
4120
4121 bool X86::isVINSERT128Index(SDNode *N) {
4122   return isVINSERTIndex(N, 128);
4123 }
4124
4125 bool X86::isVINSERT256Index(SDNode *N) {
4126   return isVINSERTIndex(N, 256);
4127 }
4128
4129 bool X86::isVEXTRACT128Index(SDNode *N) {
4130   return isVEXTRACTIndex(N, 128);
4131 }
4132
4133 bool X86::isVEXTRACT256Index(SDNode *N) {
4134   return isVEXTRACTIndex(N, 256);
4135 }
4136
4137 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4138   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4139   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4140     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4141
4142   uint64_t Index =
4143     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4144
4145   MVT VecVT = N->getOperand(0).getSimpleValueType();
4146   MVT ElVT = VecVT.getVectorElementType();
4147
4148   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4149   return Index / NumElemsPerChunk;
4150 }
4151
4152 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4153   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4154   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4155     llvm_unreachable("Illegal insert subvector for VINSERT");
4156
4157   uint64_t Index =
4158     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4159
4160   MVT VecVT = N->getSimpleValueType(0);
4161   MVT ElVT = VecVT.getVectorElementType();
4162
4163   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4164   return Index / NumElemsPerChunk;
4165 }
4166
4167 /// Return the appropriate immediate to extract the specified
4168 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4169 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4170   return getExtractVEXTRACTImmediate(N, 128);
4171 }
4172
4173 /// Return the appropriate immediate to extract the specified
4174 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4175 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4176   return getExtractVEXTRACTImmediate(N, 256);
4177 }
4178
4179 /// Return the appropriate immediate to insert at the specified
4180 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4181 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4182   return getInsertVINSERTImmediate(N, 128);
4183 }
4184
4185 /// Return the appropriate immediate to insert at the specified
4186 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4187 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4188   return getInsertVINSERTImmediate(N, 256);
4189 }
4190
4191 /// Returns true if Elt is a constant integer zero
4192 static bool isZero(SDValue V) {
4193   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4194   return C && C->isNullValue();
4195 }
4196
4197 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4198 bool X86::isZeroNode(SDValue Elt) {
4199   if (isZero(Elt))
4200     return true;
4201   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4202     return CFP->getValueAPF().isPosZero();
4203   return false;
4204 }
4205
4206 /// Returns a vector of specified type with all zero elements.
4207 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4208                              SelectionDAG &DAG, SDLoc dl) {
4209   assert(VT.isVector() && "Expected a vector type");
4210
4211   // Always build SSE zero vectors as <4 x i32> bitcasted
4212   // to their dest type. This ensures they get CSE'd.
4213   SDValue Vec;
4214   if (VT.is128BitVector()) {  // SSE
4215     if (Subtarget->hasSSE2()) {  // SSE2
4216       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4217       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4218     } else { // SSE1
4219       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4220       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4221     }
4222   } else if (VT.is256BitVector()) { // AVX
4223     if (Subtarget->hasInt256()) { // AVX2
4224       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4225       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4226       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4227     } else {
4228       // 256-bit logic and arithmetic instructions in AVX are all
4229       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4230       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4231       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4232       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4233     }
4234   } else if (VT.is512BitVector()) { // AVX-512
4235       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4236       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4237                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4238       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4239   } else if (VT.getScalarType() == MVT::i1) {
4240
4241     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4242             && "Unexpected vector type");
4243     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4244             && "Unexpected vector type");
4245     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4246     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4247     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4248   } else
4249     llvm_unreachable("Unexpected vector type");
4250
4251   return DAG.getBitcast(VT, Vec);
4252 }
4253
4254 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4255                                 SelectionDAG &DAG, SDLoc dl,
4256                                 unsigned vectorWidth) {
4257   assert((vectorWidth == 128 || vectorWidth == 256) &&
4258          "Unsupported vector width");
4259   EVT VT = Vec.getValueType();
4260   EVT ElVT = VT.getVectorElementType();
4261   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4262   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4263                                   VT.getVectorNumElements()/Factor);
4264
4265   // Extract from UNDEF is UNDEF.
4266   if (Vec.getOpcode() == ISD::UNDEF)
4267     return DAG.getUNDEF(ResultVT);
4268
4269   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4270   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4271
4272   // This is the index of the first element of the vectorWidth-bit chunk
4273   // we want.
4274   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4275                                * ElemsPerChunk);
4276
4277   // If the input is a buildvector just emit a smaller one.
4278   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4279     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4280                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4281                                     ElemsPerChunk));
4282
4283   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4284   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4285 }
4286
4287 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4288 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4289 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4290 /// instructions or a simple subregister reference. Idx is an index in the
4291 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4292 /// lowering EXTRACT_VECTOR_ELT operations easier.
4293 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4294                                    SelectionDAG &DAG, SDLoc dl) {
4295   assert((Vec.getValueType().is256BitVector() ||
4296           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4297   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4298 }
4299
4300 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4301 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4302                                    SelectionDAG &DAG, SDLoc dl) {
4303   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4304   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4305 }
4306
4307 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4308                                unsigned IdxVal, SelectionDAG &DAG,
4309                                SDLoc dl, unsigned vectorWidth) {
4310   assert((vectorWidth == 128 || vectorWidth == 256) &&
4311          "Unsupported vector width");
4312   // Inserting UNDEF is Result
4313   if (Vec.getOpcode() == ISD::UNDEF)
4314     return Result;
4315   EVT VT = Vec.getValueType();
4316   EVT ElVT = VT.getVectorElementType();
4317   EVT ResultVT = Result.getValueType();
4318
4319   // Insert the relevant vectorWidth bits.
4320   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4321
4322   // This is the index of the first element of the vectorWidth-bit chunk
4323   // we want.
4324   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4325                                * ElemsPerChunk);
4326
4327   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4328   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4329 }
4330
4331 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4332 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4333 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4334 /// simple superregister reference.  Idx is an index in the 128 bits
4335 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4336 /// lowering INSERT_VECTOR_ELT operations easier.
4337 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4338                                   SelectionDAG &DAG, SDLoc dl) {
4339   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4340
4341   // For insertion into the zero index (low half) of a 256-bit vector, it is
4342   // more efficient to generate a blend with immediate instead of an insert*128.
4343   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4344   // extend the subvector to the size of the result vector. Make sure that
4345   // we are not recursing on that node by checking for undef here.
4346   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4347       Result.getOpcode() != ISD::UNDEF) {
4348     EVT ResultVT = Result.getValueType();
4349     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4350     SDValue Undef = DAG.getUNDEF(ResultVT);
4351     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4352                                  Vec, ZeroIndex);
4353
4354     // The blend instruction, and therefore its mask, depend on the data type.
4355     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4356     if (ScalarType.isFloatingPoint()) {
4357       // Choose either vblendps (float) or vblendpd (double).
4358       unsigned ScalarSize = ScalarType.getSizeInBits();
4359       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4360       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4361       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4362       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4363     }
4364
4365     const X86Subtarget &Subtarget =
4366     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4367
4368     // AVX2 is needed for 256-bit integer blend support.
4369     // Integers must be cast to 32-bit because there is only vpblendd;
4370     // vpblendw can't be used for this because it has a handicapped mask.
4371
4372     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4373     // is still more efficient than using the wrong domain vinsertf128 that
4374     // will be created by InsertSubVector().
4375     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4376
4377     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4378     Vec256 = DAG.getBitcast(CastVT, Vec256);
4379     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4380     return DAG.getBitcast(ResultVT, Vec256);
4381   }
4382
4383   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4384 }
4385
4386 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4387                                   SelectionDAG &DAG, SDLoc dl) {
4388   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4389   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4390 }
4391
4392 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4393 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4394 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4395 /// large BUILD_VECTORS.
4396 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4397                                    unsigned NumElems, SelectionDAG &DAG,
4398                                    SDLoc dl) {
4399   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4400   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4401 }
4402
4403 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4404                                    unsigned NumElems, SelectionDAG &DAG,
4405                                    SDLoc dl) {
4406   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4407   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4408 }
4409
4410 /// Returns a vector of specified type with all bits set.
4411 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4412 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4413 /// Then bitcast to their original type, ensuring they get CSE'd.
4414 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4415                              SDLoc dl) {
4416   assert(VT.isVector() && "Expected a vector type");
4417
4418   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4419   SDValue Vec;
4420   if (VT.is256BitVector()) {
4421     if (HasInt256) { // AVX2
4422       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4423       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4424     } else { // AVX
4425       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4426       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4427     }
4428   } else if (VT.is128BitVector()) {
4429     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4430   } else
4431     llvm_unreachable("Unexpected vector type");
4432
4433   return DAG.getBitcast(VT, Vec);
4434 }
4435
4436 /// Returns a vector_shuffle node for an unpackl operation.
4437 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4438                           SDValue V2) {
4439   unsigned NumElems = VT.getVectorNumElements();
4440   SmallVector<int, 8> Mask;
4441   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4442     Mask.push_back(i);
4443     Mask.push_back(i + NumElems);
4444   }
4445   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4446 }
4447
4448 /// Returns a vector_shuffle node for an unpackh operation.
4449 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4450                           SDValue V2) {
4451   unsigned NumElems = VT.getVectorNumElements();
4452   SmallVector<int, 8> Mask;
4453   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4454     Mask.push_back(i + Half);
4455     Mask.push_back(i + NumElems + Half);
4456   }
4457   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4458 }
4459
4460 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4461 /// This produces a shuffle where the low element of V2 is swizzled into the
4462 /// zero/undef vector, landing at element Idx.
4463 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4464 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4465                                            bool IsZero,
4466                                            const X86Subtarget *Subtarget,
4467                                            SelectionDAG &DAG) {
4468   MVT VT = V2.getSimpleValueType();
4469   SDValue V1 = IsZero
4470     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4471   unsigned NumElems = VT.getVectorNumElements();
4472   SmallVector<int, 16> MaskVec;
4473   for (unsigned i = 0; i != NumElems; ++i)
4474     // If this is the insertion idx, put the low elt of V2 here.
4475     MaskVec.push_back(i == Idx ? NumElems : i);
4476   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4477 }
4478
4479 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4480 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4481 /// uses one source. Note that this will set IsUnary for shuffles which use a
4482 /// single input multiple times, and in those cases it will
4483 /// adjust the mask to only have indices within that single input.
4484 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4485 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4486                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4487   unsigned NumElems = VT.getVectorNumElements();
4488   SDValue ImmN;
4489
4490   IsUnary = false;
4491   bool IsFakeUnary = false;
4492   switch(N->getOpcode()) {
4493   case X86ISD::BLENDI:
4494     ImmN = N->getOperand(N->getNumOperands()-1);
4495     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4496     break;
4497   case X86ISD::SHUFP:
4498     ImmN = N->getOperand(N->getNumOperands()-1);
4499     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4501     break;
4502   case X86ISD::UNPCKH:
4503     DecodeUNPCKHMask(VT, Mask);
4504     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4505     break;
4506   case X86ISD::UNPCKL:
4507     DecodeUNPCKLMask(VT, Mask);
4508     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4509     break;
4510   case X86ISD::MOVHLPS:
4511     DecodeMOVHLPSMask(NumElems, Mask);
4512     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4513     break;
4514   case X86ISD::MOVLHPS:
4515     DecodeMOVLHPSMask(NumElems, Mask);
4516     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4517     break;
4518   case X86ISD::PALIGNR:
4519     ImmN = N->getOperand(N->getNumOperands()-1);
4520     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521     break;
4522   case X86ISD::PSHUFD:
4523   case X86ISD::VPERMILPI:
4524     ImmN = N->getOperand(N->getNumOperands()-1);
4525     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4526     IsUnary = true;
4527     break;
4528   case X86ISD::PSHUFHW:
4529     ImmN = N->getOperand(N->getNumOperands()-1);
4530     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4531     IsUnary = true;
4532     break;
4533   case X86ISD::PSHUFLW:
4534     ImmN = N->getOperand(N->getNumOperands()-1);
4535     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4536     IsUnary = true;
4537     break;
4538   case X86ISD::PSHUFB: {
4539     IsUnary = true;
4540     SDValue MaskNode = N->getOperand(1);
4541     while (MaskNode->getOpcode() == ISD::BITCAST)
4542       MaskNode = MaskNode->getOperand(0);
4543
4544     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4545       // If we have a build-vector, then things are easy.
4546       EVT VT = MaskNode.getValueType();
4547       assert(VT.isVector() &&
4548              "Can't produce a non-vector with a build_vector!");
4549       if (!VT.isInteger())
4550         return false;
4551
4552       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4553
4554       SmallVector<uint64_t, 32> RawMask;
4555       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4556         SDValue Op = MaskNode->getOperand(i);
4557         if (Op->getOpcode() == ISD::UNDEF) {
4558           RawMask.push_back((uint64_t)SM_SentinelUndef);
4559           continue;
4560         }
4561         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4562         if (!CN)
4563           return false;
4564         APInt MaskElement = CN->getAPIntValue();
4565
4566         // We now have to decode the element which could be any integer size and
4567         // extract each byte of it.
4568         for (int j = 0; j < NumBytesPerElement; ++j) {
4569           // Note that this is x86 and so always little endian: the low byte is
4570           // the first byte of the mask.
4571           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4572           MaskElement = MaskElement.lshr(8);
4573         }
4574       }
4575       DecodePSHUFBMask(RawMask, Mask);
4576       break;
4577     }
4578
4579     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4580     if (!MaskLoad)
4581       return false;
4582
4583     SDValue Ptr = MaskLoad->getBasePtr();
4584     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4585         Ptr->getOpcode() == X86ISD::WrapperRIP)
4586       Ptr = Ptr->getOperand(0);
4587
4588     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4589     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4590       return false;
4591
4592     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4593       DecodePSHUFBMask(C, Mask);
4594       if (Mask.empty())
4595         return false;
4596       break;
4597     }
4598
4599     return false;
4600   }
4601   case X86ISD::VPERMI:
4602     ImmN = N->getOperand(N->getNumOperands()-1);
4603     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4604     IsUnary = true;
4605     break;
4606   case X86ISD::MOVSS:
4607   case X86ISD::MOVSD:
4608     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4609     break;
4610   case X86ISD::VPERM2X128:
4611     ImmN = N->getOperand(N->getNumOperands()-1);
4612     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4613     if (Mask.empty()) return false;
4614     // Mask only contains negative index if an element is zero.
4615     if (std::any_of(Mask.begin(), Mask.end(),
4616                     [](int M){ return M == SM_SentinelZero; }))
4617       return false;
4618     break;
4619   case X86ISD::MOVSLDUP:
4620     DecodeMOVSLDUPMask(VT, Mask);
4621     IsUnary = true;
4622     break;
4623   case X86ISD::MOVSHDUP:
4624     DecodeMOVSHDUPMask(VT, Mask);
4625     IsUnary = true;
4626     break;
4627   case X86ISD::MOVDDUP:
4628     DecodeMOVDDUPMask(VT, Mask);
4629     IsUnary = true;
4630     break;
4631   case X86ISD::MOVLHPD:
4632   case X86ISD::MOVLPD:
4633   case X86ISD::MOVLPS:
4634     // Not yet implemented
4635     return false;
4636   default: llvm_unreachable("unknown target shuffle node");
4637   }
4638
4639   // If we have a fake unary shuffle, the shuffle mask is spread across two
4640   // inputs that are actually the same node. Re-map the mask to always point
4641   // into the first input.
4642   if (IsFakeUnary)
4643     for (int &M : Mask)
4644       if (M >= (int)Mask.size())
4645         M -= Mask.size();
4646
4647   return true;
4648 }
4649
4650 /// Returns the scalar element that will make up the ith
4651 /// element of the result of the vector shuffle.
4652 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4653                                    unsigned Depth) {
4654   if (Depth == 6)
4655     return SDValue();  // Limit search depth.
4656
4657   SDValue V = SDValue(N, 0);
4658   EVT VT = V.getValueType();
4659   unsigned Opcode = V.getOpcode();
4660
4661   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4662   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4663     int Elt = SV->getMaskElt(Index);
4664
4665     if (Elt < 0)
4666       return DAG.getUNDEF(VT.getVectorElementType());
4667
4668     unsigned NumElems = VT.getVectorNumElements();
4669     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4670                                          : SV->getOperand(1);
4671     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4672   }
4673
4674   // Recurse into target specific vector shuffles to find scalars.
4675   if (isTargetShuffle(Opcode)) {
4676     MVT ShufVT = V.getSimpleValueType();
4677     unsigned NumElems = ShufVT.getVectorNumElements();
4678     SmallVector<int, 16> ShuffleMask;
4679     bool IsUnary;
4680
4681     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4682       return SDValue();
4683
4684     int Elt = ShuffleMask[Index];
4685     if (Elt < 0)
4686       return DAG.getUNDEF(ShufVT.getVectorElementType());
4687
4688     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4689                                          : N->getOperand(1);
4690     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4691                                Depth+1);
4692   }
4693
4694   // Actual nodes that may contain scalar elements
4695   if (Opcode == ISD::BITCAST) {
4696     V = V.getOperand(0);
4697     EVT SrcVT = V.getValueType();
4698     unsigned NumElems = VT.getVectorNumElements();
4699
4700     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4701       return SDValue();
4702   }
4703
4704   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4705     return (Index == 0) ? V.getOperand(0)
4706                         : DAG.getUNDEF(VT.getVectorElementType());
4707
4708   if (V.getOpcode() == ISD::BUILD_VECTOR)
4709     return V.getOperand(Index);
4710
4711   return SDValue();
4712 }
4713
4714 /// Custom lower build_vector of v16i8.
4715 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4716                                        unsigned NumNonZero, unsigned NumZero,
4717                                        SelectionDAG &DAG,
4718                                        const X86Subtarget* Subtarget,
4719                                        const TargetLowering &TLI) {
4720   if (NumNonZero > 8)
4721     return SDValue();
4722
4723   SDLoc dl(Op);
4724   SDValue V;
4725   bool First = true;
4726
4727   // SSE4.1 - use PINSRB to insert each byte directly.
4728   if (Subtarget->hasSSE41()) {
4729     for (unsigned i = 0; i < 16; ++i) {
4730       bool isNonZero = (NonZeros & (1 << i)) != 0;
4731       if (isNonZero) {
4732         if (First) {
4733           if (NumZero)
4734             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4735           else
4736             V = DAG.getUNDEF(MVT::v16i8);
4737           First = false;
4738         }
4739         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4740                         MVT::v16i8, V, Op.getOperand(i),
4741                         DAG.getIntPtrConstant(i, dl));
4742       }
4743     }
4744
4745     return V;
4746   }
4747
4748   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4749   for (unsigned i = 0; i < 16; ++i) {
4750     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4751     if (ThisIsNonZero && First) {
4752       if (NumZero)
4753         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4754       else
4755         V = DAG.getUNDEF(MVT::v8i16);
4756       First = false;
4757     }
4758
4759     if ((i & 1) != 0) {
4760       SDValue ThisElt, LastElt;
4761       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4762       if (LastIsNonZero) {
4763         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4764                               MVT::i16, Op.getOperand(i-1));
4765       }
4766       if (ThisIsNonZero) {
4767         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4768         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4769                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4770         if (LastIsNonZero)
4771           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4772       } else
4773         ThisElt = LastElt;
4774
4775       if (ThisElt.getNode())
4776         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4777                         DAG.getIntPtrConstant(i/2, dl));
4778     }
4779   }
4780
4781   return DAG.getBitcast(MVT::v16i8, V);
4782 }
4783
4784 /// Custom lower build_vector of v8i16.
4785 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4786                                      unsigned NumNonZero, unsigned NumZero,
4787                                      SelectionDAG &DAG,
4788                                      const X86Subtarget* Subtarget,
4789                                      const TargetLowering &TLI) {
4790   if (NumNonZero > 4)
4791     return SDValue();
4792
4793   SDLoc dl(Op);
4794   SDValue V;
4795   bool First = true;
4796   for (unsigned i = 0; i < 8; ++i) {
4797     bool isNonZero = (NonZeros & (1 << i)) != 0;
4798     if (isNonZero) {
4799       if (First) {
4800         if (NumZero)
4801           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4802         else
4803           V = DAG.getUNDEF(MVT::v8i16);
4804         First = false;
4805       }
4806       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4807                       MVT::v8i16, V, Op.getOperand(i),
4808                       DAG.getIntPtrConstant(i, dl));
4809     }
4810   }
4811
4812   return V;
4813 }
4814
4815 /// Custom lower build_vector of v4i32 or v4f32.
4816 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4817                                      const X86Subtarget *Subtarget,
4818                                      const TargetLowering &TLI) {
4819   // Find all zeroable elements.
4820   std::bitset<4> Zeroable;
4821   for (int i=0; i < 4; ++i) {
4822     SDValue Elt = Op->getOperand(i);
4823     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4824   }
4825   assert(Zeroable.size() - Zeroable.count() > 1 &&
4826          "We expect at least two non-zero elements!");
4827
4828   // We only know how to deal with build_vector nodes where elements are either
4829   // zeroable or extract_vector_elt with constant index.
4830   SDValue FirstNonZero;
4831   unsigned FirstNonZeroIdx;
4832   for (unsigned i=0; i < 4; ++i) {
4833     if (Zeroable[i])
4834       continue;
4835     SDValue Elt = Op->getOperand(i);
4836     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4837         !isa<ConstantSDNode>(Elt.getOperand(1)))
4838       return SDValue();
4839     // Make sure that this node is extracting from a 128-bit vector.
4840     MVT VT = Elt.getOperand(0).getSimpleValueType();
4841     if (!VT.is128BitVector())
4842       return SDValue();
4843     if (!FirstNonZero.getNode()) {
4844       FirstNonZero = Elt;
4845       FirstNonZeroIdx = i;
4846     }
4847   }
4848
4849   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4850   SDValue V1 = FirstNonZero.getOperand(0);
4851   MVT VT = V1.getSimpleValueType();
4852
4853   // See if this build_vector can be lowered as a blend with zero.
4854   SDValue Elt;
4855   unsigned EltMaskIdx, EltIdx;
4856   int Mask[4];
4857   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4858     if (Zeroable[EltIdx]) {
4859       // The zero vector will be on the right hand side.
4860       Mask[EltIdx] = EltIdx+4;
4861       continue;
4862     }
4863
4864     Elt = Op->getOperand(EltIdx);
4865     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4866     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4867     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4868       break;
4869     Mask[EltIdx] = EltIdx;
4870   }
4871
4872   if (EltIdx == 4) {
4873     // Let the shuffle legalizer deal with blend operations.
4874     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4875     if (V1.getSimpleValueType() != VT)
4876       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4877     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4878   }
4879
4880   // See if we can lower this build_vector to a INSERTPS.
4881   if (!Subtarget->hasSSE41())
4882     return SDValue();
4883
4884   SDValue V2 = Elt.getOperand(0);
4885   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4886     V1 = SDValue();
4887
4888   bool CanFold = true;
4889   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4890     if (Zeroable[i])
4891       continue;
4892
4893     SDValue Current = Op->getOperand(i);
4894     SDValue SrcVector = Current->getOperand(0);
4895     if (!V1.getNode())
4896       V1 = SrcVector;
4897     CanFold = SrcVector == V1 &&
4898       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4899   }
4900
4901   if (!CanFold)
4902     return SDValue();
4903
4904   assert(V1.getNode() && "Expected at least two non-zero elements!");
4905   if (V1.getSimpleValueType() != MVT::v4f32)
4906     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4907   if (V2.getSimpleValueType() != MVT::v4f32)
4908     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4909
4910   // Ok, we can emit an INSERTPS instruction.
4911   unsigned ZMask = Zeroable.to_ulong();
4912
4913   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4914   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4915   SDLoc DL(Op);
4916   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4917                                DAG.getIntPtrConstant(InsertPSMask, DL));
4918   return DAG.getBitcast(VT, Result);
4919 }
4920
4921 /// Return a vector logical shift node.
4922 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4923                          unsigned NumBits, SelectionDAG &DAG,
4924                          const TargetLowering &TLI, SDLoc dl) {
4925   assert(VT.is128BitVector() && "Unknown type for VShift");
4926   MVT ShVT = MVT::v2i64;
4927   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4928   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4929   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4930   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4931   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4932   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4933 }
4934
4935 static SDValue
4936 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4937
4938   // Check if the scalar load can be widened into a vector load. And if
4939   // the address is "base + cst" see if the cst can be "absorbed" into
4940   // the shuffle mask.
4941   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4942     SDValue Ptr = LD->getBasePtr();
4943     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4944       return SDValue();
4945     EVT PVT = LD->getValueType(0);
4946     if (PVT != MVT::i32 && PVT != MVT::f32)
4947       return SDValue();
4948
4949     int FI = -1;
4950     int64_t Offset = 0;
4951     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4952       FI = FINode->getIndex();
4953       Offset = 0;
4954     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4955                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4956       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4957       Offset = Ptr.getConstantOperandVal(1);
4958       Ptr = Ptr.getOperand(0);
4959     } else {
4960       return SDValue();
4961     }
4962
4963     // FIXME: 256-bit vector instructions don't require a strict alignment,
4964     // improve this code to support it better.
4965     unsigned RequiredAlign = VT.getSizeInBits()/8;
4966     SDValue Chain = LD->getChain();
4967     // Make sure the stack object alignment is at least 16 or 32.
4968     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4969     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4970       if (MFI->isFixedObjectIndex(FI)) {
4971         // Can't change the alignment. FIXME: It's possible to compute
4972         // the exact stack offset and reference FI + adjust offset instead.
4973         // If someone *really* cares about this. That's the way to implement it.
4974         return SDValue();
4975       } else {
4976         MFI->setObjectAlignment(FI, RequiredAlign);
4977       }
4978     }
4979
4980     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4981     // Ptr + (Offset & ~15).
4982     if (Offset < 0)
4983       return SDValue();
4984     if ((Offset % RequiredAlign) & 3)
4985       return SDValue();
4986     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4987     if (StartOffset) {
4988       SDLoc DL(Ptr);
4989       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4990                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4991     }
4992
4993     int EltNo = (Offset - StartOffset) >> 2;
4994     unsigned NumElems = VT.getVectorNumElements();
4995
4996     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4997     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4998                              LD->getPointerInfo().getWithOffset(StartOffset),
4999                              false, false, false, 0);
5000
5001     SmallVector<int, 8> Mask(NumElems, EltNo);
5002
5003     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5004   }
5005
5006   return SDValue();
5007 }
5008
5009 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5010 /// elements can be replaced by a single large load which has the same value as
5011 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5012 ///
5013 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5014 ///
5015 /// FIXME: we'd also like to handle the case where the last elements are zero
5016 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5017 /// There's even a handy isZeroNode for that purpose.
5018 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5019                                         SDLoc &DL, SelectionDAG &DAG,
5020                                         bool isAfterLegalize) {
5021   unsigned NumElems = Elts.size();
5022
5023   LoadSDNode *LDBase = nullptr;
5024   unsigned LastLoadedElt = -1U;
5025
5026   // For each element in the initializer, see if we've found a load or an undef.
5027   // If we don't find an initial load element, or later load elements are
5028   // non-consecutive, bail out.
5029   for (unsigned i = 0; i < NumElems; ++i) {
5030     SDValue Elt = Elts[i];
5031     // Look through a bitcast.
5032     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5033       Elt = Elt.getOperand(0);
5034     if (!Elt.getNode() ||
5035         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5036       return SDValue();
5037     if (!LDBase) {
5038       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5039         return SDValue();
5040       LDBase = cast<LoadSDNode>(Elt.getNode());
5041       LastLoadedElt = i;
5042       continue;
5043     }
5044     if (Elt.getOpcode() == ISD::UNDEF)
5045       continue;
5046
5047     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5048     EVT LdVT = Elt.getValueType();
5049     // Each loaded element must be the correct fractional portion of the
5050     // requested vector load.
5051     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5052       return SDValue();
5053     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5054       return SDValue();
5055     LastLoadedElt = i;
5056   }
5057
5058   // If we have found an entire vector of loads and undefs, then return a large
5059   // load of the entire vector width starting at the base pointer.  If we found
5060   // consecutive loads for the low half, generate a vzext_load node.
5061   if (LastLoadedElt == NumElems - 1) {
5062     assert(LDBase && "Did not find base load for merging consecutive loads");
5063     EVT EltVT = LDBase->getValueType(0);
5064     // Ensure that the input vector size for the merged loads matches the
5065     // cumulative size of the input elements.
5066     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5067       return SDValue();
5068
5069     if (isAfterLegalize &&
5070         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5071       return SDValue();
5072
5073     SDValue NewLd = SDValue();
5074
5075     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5076                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5077                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5078                         LDBase->getAlignment());
5079
5080     if (LDBase->hasAnyUseOfValue(1)) {
5081       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5082                                      SDValue(LDBase, 1),
5083                                      SDValue(NewLd.getNode(), 1));
5084       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5085       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5086                              SDValue(NewLd.getNode(), 1));
5087     }
5088
5089     return NewLd;
5090   }
5091
5092   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5093   //of a v4i32 / v4f32. It's probably worth generalizing.
5094   EVT EltVT = VT.getVectorElementType();
5095   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5096       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5097     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5098     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5099     SDValue ResNode =
5100         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5101                                 LDBase->getPointerInfo(),
5102                                 LDBase->getAlignment(),
5103                                 false/*isVolatile*/, true/*ReadMem*/,
5104                                 false/*WriteMem*/);
5105
5106     // Make sure the newly-created LOAD is in the same position as LDBase in
5107     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5108     // update uses of LDBase's output chain to use the TokenFactor.
5109     if (LDBase->hasAnyUseOfValue(1)) {
5110       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5111                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5112       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5113       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5114                              SDValue(ResNode.getNode(), 1));
5115     }
5116
5117     return DAG.getBitcast(VT, ResNode);
5118   }
5119   return SDValue();
5120 }
5121
5122 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5123 /// to generate a splat value for the following cases:
5124 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5125 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5126 /// a scalar load, or a constant.
5127 /// The VBROADCAST node is returned when a pattern is found,
5128 /// or SDValue() otherwise.
5129 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5130                                     SelectionDAG &DAG) {
5131   // VBROADCAST requires AVX.
5132   // TODO: Splats could be generated for non-AVX CPUs using SSE
5133   // instructions, but there's less potential gain for only 128-bit vectors.
5134   if (!Subtarget->hasAVX())
5135     return SDValue();
5136
5137   MVT VT = Op.getSimpleValueType();
5138   SDLoc dl(Op);
5139
5140   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5141          "Unsupported vector type for broadcast.");
5142
5143   SDValue Ld;
5144   bool ConstSplatVal;
5145
5146   switch (Op.getOpcode()) {
5147     default:
5148       // Unknown pattern found.
5149       return SDValue();
5150
5151     case ISD::BUILD_VECTOR: {
5152       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5153       BitVector UndefElements;
5154       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5155
5156       // We need a splat of a single value to use broadcast, and it doesn't
5157       // make any sense if the value is only in one element of the vector.
5158       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5159         return SDValue();
5160
5161       Ld = Splat;
5162       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5163                        Ld.getOpcode() == ISD::ConstantFP);
5164
5165       // Make sure that all of the users of a non-constant load are from the
5166       // BUILD_VECTOR node.
5167       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5168         return SDValue();
5169       break;
5170     }
5171
5172     case ISD::VECTOR_SHUFFLE: {
5173       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5174
5175       // Shuffles must have a splat mask where the first element is
5176       // broadcasted.
5177       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5178         return SDValue();
5179
5180       SDValue Sc = Op.getOperand(0);
5181       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5182           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5183
5184         if (!Subtarget->hasInt256())
5185           return SDValue();
5186
5187         // Use the register form of the broadcast instruction available on AVX2.
5188         if (VT.getSizeInBits() >= 256)
5189           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5190         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5191       }
5192
5193       Ld = Sc.getOperand(0);
5194       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5195                        Ld.getOpcode() == ISD::ConstantFP);
5196
5197       // The scalar_to_vector node and the suspected
5198       // load node must have exactly one user.
5199       // Constants may have multiple users.
5200
5201       // AVX-512 has register version of the broadcast
5202       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5203         Ld.getValueType().getSizeInBits() >= 32;
5204       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5205           !hasRegVer))
5206         return SDValue();
5207       break;
5208     }
5209   }
5210
5211   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5212   bool IsGE256 = (VT.getSizeInBits() >= 256);
5213
5214   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5215   // instruction to save 8 or more bytes of constant pool data.
5216   // TODO: If multiple splats are generated to load the same constant,
5217   // it may be detrimental to overall size. There needs to be a way to detect
5218   // that condition to know if this is truly a size win.
5219   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5220
5221   // Handle broadcasting a single constant scalar from the constant pool
5222   // into a vector.
5223   // On Sandybridge (no AVX2), it is still better to load a constant vector
5224   // from the constant pool and not to broadcast it from a scalar.
5225   // But override that restriction when optimizing for size.
5226   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5227   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5228     EVT CVT = Ld.getValueType();
5229     assert(!CVT.isVector() && "Must not broadcast a vector type");
5230
5231     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5232     // For size optimization, also splat v2f64 and v2i64, and for size opt
5233     // with AVX2, also splat i8 and i16.
5234     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5235     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5236         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5237       const Constant *C = nullptr;
5238       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5239         C = CI->getConstantIntValue();
5240       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5241         C = CF->getConstantFPValue();
5242
5243       assert(C && "Invalid constant type");
5244
5245       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5246       SDValue CP =
5247           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5248       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5249       Ld = DAG.getLoad(
5250           CVT, dl, DAG.getEntryNode(), CP,
5251           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5252           false, false, Alignment);
5253
5254       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5255     }
5256   }
5257
5258   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5259
5260   // Handle AVX2 in-register broadcasts.
5261   if (!IsLoad && Subtarget->hasInt256() &&
5262       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5263     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5264
5265   // The scalar source must be a normal load.
5266   if (!IsLoad)
5267     return SDValue();
5268
5269   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5270       (Subtarget->hasVLX() && ScalarSize == 64))
5271     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5272
5273   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5274   // double since there is no vbroadcastsd xmm
5275   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5276     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5277       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5278   }
5279
5280   // Unsupported broadcast.
5281   return SDValue();
5282 }
5283
5284 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5285 /// underlying vector and index.
5286 ///
5287 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5288 /// index.
5289 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5290                                          SDValue ExtIdx) {
5291   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5292   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5293     return Idx;
5294
5295   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5296   // lowered this:
5297   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5298   // to:
5299   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5300   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5301   //                           undef)
5302   //                       Constant<0>)
5303   // In this case the vector is the extract_subvector expression and the index
5304   // is 2, as specified by the shuffle.
5305   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5306   SDValue ShuffleVec = SVOp->getOperand(0);
5307   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5308   assert(ShuffleVecVT.getVectorElementType() ==
5309          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5310
5311   int ShuffleIdx = SVOp->getMaskElt(Idx);
5312   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5313     ExtractedFromVec = ShuffleVec;
5314     return ShuffleIdx;
5315   }
5316   return Idx;
5317 }
5318
5319 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5320   MVT VT = Op.getSimpleValueType();
5321
5322   // Skip if insert_vec_elt is not supported.
5323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5324   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5325     return SDValue();
5326
5327   SDLoc DL(Op);
5328   unsigned NumElems = Op.getNumOperands();
5329
5330   SDValue VecIn1;
5331   SDValue VecIn2;
5332   SmallVector<unsigned, 4> InsertIndices;
5333   SmallVector<int, 8> Mask(NumElems, -1);
5334
5335   for (unsigned i = 0; i != NumElems; ++i) {
5336     unsigned Opc = Op.getOperand(i).getOpcode();
5337
5338     if (Opc == ISD::UNDEF)
5339       continue;
5340
5341     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5342       // Quit if more than 1 elements need inserting.
5343       if (InsertIndices.size() > 1)
5344         return SDValue();
5345
5346       InsertIndices.push_back(i);
5347       continue;
5348     }
5349
5350     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5351     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5352     // Quit if non-constant index.
5353     if (!isa<ConstantSDNode>(ExtIdx))
5354       return SDValue();
5355     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5356
5357     // Quit if extracted from vector of different type.
5358     if (ExtractedFromVec.getValueType() != VT)
5359       return SDValue();
5360
5361     if (!VecIn1.getNode())
5362       VecIn1 = ExtractedFromVec;
5363     else if (VecIn1 != ExtractedFromVec) {
5364       if (!VecIn2.getNode())
5365         VecIn2 = ExtractedFromVec;
5366       else if (VecIn2 != ExtractedFromVec)
5367         // Quit if more than 2 vectors to shuffle
5368         return SDValue();
5369     }
5370
5371     if (ExtractedFromVec == VecIn1)
5372       Mask[i] = Idx;
5373     else if (ExtractedFromVec == VecIn2)
5374       Mask[i] = Idx + NumElems;
5375   }
5376
5377   if (!VecIn1.getNode())
5378     return SDValue();
5379
5380   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5381   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5382   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5383     unsigned Idx = InsertIndices[i];
5384     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5385                      DAG.getIntPtrConstant(Idx, DL));
5386   }
5387
5388   return NV;
5389 }
5390
5391 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5392   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5393          Op.getScalarValueSizeInBits() == 1 &&
5394          "Can not convert non-constant vector");
5395   uint64_t Immediate = 0;
5396   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5397     SDValue In = Op.getOperand(idx);
5398     if (In.getOpcode() != ISD::UNDEF)
5399       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5400   }
5401   SDLoc dl(Op);
5402   MVT VT =
5403    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5404   return DAG.getConstant(Immediate, dl, VT);
5405 }
5406 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5407 SDValue
5408 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5409
5410   MVT VT = Op.getSimpleValueType();
5411   assert((VT.getVectorElementType() == MVT::i1) &&
5412          "Unexpected type in LowerBUILD_VECTORvXi1!");
5413
5414   SDLoc dl(Op);
5415   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5416     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5417     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5418     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5419   }
5420
5421   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5422     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5423     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5424     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5425   }
5426
5427   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5428     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5429     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5430       return DAG.getBitcast(VT, Imm);
5431     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5432     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5433                         DAG.getIntPtrConstant(0, dl));
5434   }
5435
5436   // Vector has one or more non-const elements
5437   uint64_t Immediate = 0;
5438   SmallVector<unsigned, 16> NonConstIdx;
5439   bool IsSplat = true;
5440   bool HasConstElts = false;
5441   int SplatIdx = -1;
5442   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5443     SDValue In = Op.getOperand(idx);
5444     if (In.getOpcode() == ISD::UNDEF)
5445       continue;
5446     if (!isa<ConstantSDNode>(In))
5447       NonConstIdx.push_back(idx);
5448     else {
5449       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5450       HasConstElts = true;
5451     }
5452     if (SplatIdx == -1)
5453       SplatIdx = idx;
5454     else if (In != Op.getOperand(SplatIdx))
5455       IsSplat = false;
5456   }
5457
5458   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5459   if (IsSplat)
5460     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5461                        DAG.getConstant(1, dl, VT),
5462                        DAG.getConstant(0, dl, VT));
5463
5464   // insert elements one by one
5465   SDValue DstVec;
5466   SDValue Imm;
5467   if (Immediate) {
5468     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5469     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5470   }
5471   else if (HasConstElts)
5472     Imm = DAG.getConstant(0, dl, VT);
5473   else
5474     Imm = DAG.getUNDEF(VT);
5475   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5476     DstVec = DAG.getBitcast(VT, Imm);
5477   else {
5478     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5479     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5480                          DAG.getIntPtrConstant(0, dl));
5481   }
5482
5483   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5484     unsigned InsertIdx = NonConstIdx[i];
5485     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5486                          Op.getOperand(InsertIdx),
5487                          DAG.getIntPtrConstant(InsertIdx, dl));
5488   }
5489   return DstVec;
5490 }
5491
5492 /// \brief Return true if \p N implements a horizontal binop and return the
5493 /// operands for the horizontal binop into V0 and V1.
5494 ///
5495 /// This is a helper function of LowerToHorizontalOp().
5496 /// This function checks that the build_vector \p N in input implements a
5497 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5498 /// operation to match.
5499 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5500 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5501 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5502 /// arithmetic sub.
5503 ///
5504 /// This function only analyzes elements of \p N whose indices are
5505 /// in range [BaseIdx, LastIdx).
5506 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5507                               SelectionDAG &DAG,
5508                               unsigned BaseIdx, unsigned LastIdx,
5509                               SDValue &V0, SDValue &V1) {
5510   EVT VT = N->getValueType(0);
5511
5512   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5513   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5514          "Invalid Vector in input!");
5515
5516   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5517   bool CanFold = true;
5518   unsigned ExpectedVExtractIdx = BaseIdx;
5519   unsigned NumElts = LastIdx - BaseIdx;
5520   V0 = DAG.getUNDEF(VT);
5521   V1 = DAG.getUNDEF(VT);
5522
5523   // Check if N implements a horizontal binop.
5524   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5525     SDValue Op = N->getOperand(i + BaseIdx);
5526
5527     // Skip UNDEFs.
5528     if (Op->getOpcode() == ISD::UNDEF) {
5529       // Update the expected vector extract index.
5530       if (i * 2 == NumElts)
5531         ExpectedVExtractIdx = BaseIdx;
5532       ExpectedVExtractIdx += 2;
5533       continue;
5534     }
5535
5536     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5537
5538     if (!CanFold)
5539       break;
5540
5541     SDValue Op0 = Op.getOperand(0);
5542     SDValue Op1 = Op.getOperand(1);
5543
5544     // Try to match the following pattern:
5545     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5546     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5547         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5548         Op0.getOperand(0) == Op1.getOperand(0) &&
5549         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5550         isa<ConstantSDNode>(Op1.getOperand(1)));
5551     if (!CanFold)
5552       break;
5553
5554     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5555     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5556
5557     if (i * 2 < NumElts) {
5558       if (V0.getOpcode() == ISD::UNDEF) {
5559         V0 = Op0.getOperand(0);
5560         if (V0.getValueType() != VT)
5561           return false;
5562       }
5563     } else {
5564       if (V1.getOpcode() == ISD::UNDEF) {
5565         V1 = Op0.getOperand(0);
5566         if (V1.getValueType() != VT)
5567           return false;
5568       }
5569       if (i * 2 == NumElts)
5570         ExpectedVExtractIdx = BaseIdx;
5571     }
5572
5573     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5574     if (I0 == ExpectedVExtractIdx)
5575       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5576     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5577       // Try to match the following dag sequence:
5578       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5579       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5580     } else
5581       CanFold = false;
5582
5583     ExpectedVExtractIdx += 2;
5584   }
5585
5586   return CanFold;
5587 }
5588
5589 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5590 /// a concat_vector.
5591 ///
5592 /// This is a helper function of LowerToHorizontalOp().
5593 /// This function expects two 256-bit vectors called V0 and V1.
5594 /// At first, each vector is split into two separate 128-bit vectors.
5595 /// Then, the resulting 128-bit vectors are used to implement two
5596 /// horizontal binary operations.
5597 ///
5598 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5599 ///
5600 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5601 /// the two new horizontal binop.
5602 /// When Mode is set, the first horizontal binop dag node would take as input
5603 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5604 /// horizontal binop dag node would take as input the lower 128-bit of V1
5605 /// and the upper 128-bit of V1.
5606 ///   Example:
5607 ///     HADD V0_LO, V0_HI
5608 ///     HADD V1_LO, V1_HI
5609 ///
5610 /// Otherwise, the first horizontal binop dag node takes as input the lower
5611 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5612 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5613 ///   Example:
5614 ///     HADD V0_LO, V1_LO
5615 ///     HADD V0_HI, V1_HI
5616 ///
5617 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5618 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5619 /// the upper 128-bits of the result.
5620 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5621                                      SDLoc DL, SelectionDAG &DAG,
5622                                      unsigned X86Opcode, bool Mode,
5623                                      bool isUndefLO, bool isUndefHI) {
5624   EVT VT = V0.getValueType();
5625   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5626          "Invalid nodes in input!");
5627
5628   unsigned NumElts = VT.getVectorNumElements();
5629   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5630   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5631   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5632   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5633   EVT NewVT = V0_LO.getValueType();
5634
5635   SDValue LO = DAG.getUNDEF(NewVT);
5636   SDValue HI = DAG.getUNDEF(NewVT);
5637
5638   if (Mode) {
5639     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5640     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5641       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5642     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5643       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5644   } else {
5645     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5646     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5647                        V1_LO->getOpcode() != ISD::UNDEF))
5648       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5649
5650     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5651                        V1_HI->getOpcode() != ISD::UNDEF))
5652       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5653   }
5654
5655   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5656 }
5657
5658 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5659 /// node.
5660 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5661                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5662   EVT VT = BV->getValueType(0);
5663   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5664       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5665     return SDValue();
5666
5667   SDLoc DL(BV);
5668   unsigned NumElts = VT.getVectorNumElements();
5669   SDValue InVec0 = DAG.getUNDEF(VT);
5670   SDValue InVec1 = DAG.getUNDEF(VT);
5671
5672   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5673           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5674
5675   // Odd-numbered elements in the input build vector are obtained from
5676   // adding two integer/float elements.
5677   // Even-numbered elements in the input build vector are obtained from
5678   // subtracting two integer/float elements.
5679   unsigned ExpectedOpcode = ISD::FSUB;
5680   unsigned NextExpectedOpcode = ISD::FADD;
5681   bool AddFound = false;
5682   bool SubFound = false;
5683
5684   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5685     SDValue Op = BV->getOperand(i);
5686
5687     // Skip 'undef' values.
5688     unsigned Opcode = Op.getOpcode();
5689     if (Opcode == ISD::UNDEF) {
5690       std::swap(ExpectedOpcode, NextExpectedOpcode);
5691       continue;
5692     }
5693
5694     // Early exit if we found an unexpected opcode.
5695     if (Opcode != ExpectedOpcode)
5696       return SDValue();
5697
5698     SDValue Op0 = Op.getOperand(0);
5699     SDValue Op1 = Op.getOperand(1);
5700
5701     // Try to match the following pattern:
5702     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5703     // Early exit if we cannot match that sequence.
5704     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5705         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5706         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5707         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5708         Op0.getOperand(1) != Op1.getOperand(1))
5709       return SDValue();
5710
5711     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5712     if (I0 != i)
5713       return SDValue();
5714
5715     // We found a valid add/sub node. Update the information accordingly.
5716     if (i & 1)
5717       AddFound = true;
5718     else
5719       SubFound = true;
5720
5721     // Update InVec0 and InVec1.
5722     if (InVec0.getOpcode() == ISD::UNDEF) {
5723       InVec0 = Op0.getOperand(0);
5724       if (InVec0.getValueType() != VT)
5725         return SDValue();
5726     }
5727     if (InVec1.getOpcode() == ISD::UNDEF) {
5728       InVec1 = Op1.getOperand(0);
5729       if (InVec1.getValueType() != VT)
5730         return SDValue();
5731     }
5732
5733     // Make sure that operands in input to each add/sub node always
5734     // come from a same pair of vectors.
5735     if (InVec0 != Op0.getOperand(0)) {
5736       if (ExpectedOpcode == ISD::FSUB)
5737         return SDValue();
5738
5739       // FADD is commutable. Try to commute the operands
5740       // and then test again.
5741       std::swap(Op0, Op1);
5742       if (InVec0 != Op0.getOperand(0))
5743         return SDValue();
5744     }
5745
5746     if (InVec1 != Op1.getOperand(0))
5747       return SDValue();
5748
5749     // Update the pair of expected opcodes.
5750     std::swap(ExpectedOpcode, NextExpectedOpcode);
5751   }
5752
5753   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5754   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5755       InVec1.getOpcode() != ISD::UNDEF)
5756     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5757
5758   return SDValue();
5759 }
5760
5761 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5762 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5763                                    const X86Subtarget *Subtarget,
5764                                    SelectionDAG &DAG) {
5765   EVT VT = BV->getValueType(0);
5766   unsigned NumElts = VT.getVectorNumElements();
5767   unsigned NumUndefsLO = 0;
5768   unsigned NumUndefsHI = 0;
5769   unsigned Half = NumElts/2;
5770
5771   // Count the number of UNDEF operands in the build_vector in input.
5772   for (unsigned i = 0, e = Half; i != e; ++i)
5773     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5774       NumUndefsLO++;
5775
5776   for (unsigned i = Half, e = NumElts; i != e; ++i)
5777     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5778       NumUndefsHI++;
5779
5780   // Early exit if this is either a build_vector of all UNDEFs or all the
5781   // operands but one are UNDEF.
5782   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5783     return SDValue();
5784
5785   SDLoc DL(BV);
5786   SDValue InVec0, InVec1;
5787   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5788     // Try to match an SSE3 float HADD/HSUB.
5789     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5790       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5791
5792     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5793       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5794   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5795     // Try to match an SSSE3 integer HADD/HSUB.
5796     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5797       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5798
5799     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5800       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5801   }
5802
5803   if (!Subtarget->hasAVX())
5804     return SDValue();
5805
5806   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5807     // Try to match an AVX horizontal add/sub of packed single/double
5808     // precision floating point values from 256-bit vectors.
5809     SDValue InVec2, InVec3;
5810     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5811         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5812         ((InVec0.getOpcode() == ISD::UNDEF ||
5813           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5814         ((InVec1.getOpcode() == ISD::UNDEF ||
5815           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5816       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5817
5818     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5819         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5820         ((InVec0.getOpcode() == ISD::UNDEF ||
5821           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5822         ((InVec1.getOpcode() == ISD::UNDEF ||
5823           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5824       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5825   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5826     // Try to match an AVX2 horizontal add/sub of signed integers.
5827     SDValue InVec2, InVec3;
5828     unsigned X86Opcode;
5829     bool CanFold = true;
5830
5831     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5832         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5833         ((InVec0.getOpcode() == ISD::UNDEF ||
5834           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5835         ((InVec1.getOpcode() == ISD::UNDEF ||
5836           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5837       X86Opcode = X86ISD::HADD;
5838     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5839         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5840         ((InVec0.getOpcode() == ISD::UNDEF ||
5841           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5842         ((InVec1.getOpcode() == ISD::UNDEF ||
5843           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5844       X86Opcode = X86ISD::HSUB;
5845     else
5846       CanFold = false;
5847
5848     if (CanFold) {
5849       // Fold this build_vector into a single horizontal add/sub.
5850       // Do this only if the target has AVX2.
5851       if (Subtarget->hasAVX2())
5852         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5853
5854       // Do not try to expand this build_vector into a pair of horizontal
5855       // add/sub if we can emit a pair of scalar add/sub.
5856       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5857         return SDValue();
5858
5859       // Convert this build_vector into a pair of horizontal binop followed by
5860       // a concat vector.
5861       bool isUndefLO = NumUndefsLO == Half;
5862       bool isUndefHI = NumUndefsHI == Half;
5863       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5864                                    isUndefLO, isUndefHI);
5865     }
5866   }
5867
5868   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5869        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5870     unsigned X86Opcode;
5871     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5872       X86Opcode = X86ISD::HADD;
5873     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5874       X86Opcode = X86ISD::HSUB;
5875     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5876       X86Opcode = X86ISD::FHADD;
5877     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5878       X86Opcode = X86ISD::FHSUB;
5879     else
5880       return SDValue();
5881
5882     // Don't try to expand this build_vector into a pair of horizontal add/sub
5883     // if we can simply emit a pair of scalar add/sub.
5884     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5885       return SDValue();
5886
5887     // Convert this build_vector into two horizontal add/sub followed by
5888     // a concat vector.
5889     bool isUndefLO = NumUndefsLO == Half;
5890     bool isUndefHI = NumUndefsHI == Half;
5891     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5892                                  isUndefLO, isUndefHI);
5893   }
5894
5895   return SDValue();
5896 }
5897
5898 SDValue
5899 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5900   SDLoc dl(Op);
5901
5902   MVT VT = Op.getSimpleValueType();
5903   MVT ExtVT = VT.getVectorElementType();
5904   unsigned NumElems = Op.getNumOperands();
5905
5906   // Generate vectors for predicate vectors.
5907   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5908     return LowerBUILD_VECTORvXi1(Op, DAG);
5909
5910   // Vectors containing all zeros can be matched by pxor and xorps later
5911   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5912     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5913     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5914     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5915       return Op;
5916
5917     return getZeroVector(VT, Subtarget, DAG, dl);
5918   }
5919
5920   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5921   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5922   // vpcmpeqd on 256-bit vectors.
5923   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5924     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5925       return Op;
5926
5927     if (!VT.is512BitVector())
5928       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5929   }
5930
5931   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5932   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5933     return AddSub;
5934   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5935     return HorizontalOp;
5936   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5937     return Broadcast;
5938
5939   unsigned EVTBits = ExtVT.getSizeInBits();
5940
5941   unsigned NumZero  = 0;
5942   unsigned NumNonZero = 0;
5943   unsigned NonZeros = 0;
5944   bool IsAllConstants = true;
5945   SmallSet<SDValue, 8> Values;
5946   for (unsigned i = 0; i < NumElems; ++i) {
5947     SDValue Elt = Op.getOperand(i);
5948     if (Elt.getOpcode() == ISD::UNDEF)
5949       continue;
5950     Values.insert(Elt);
5951     if (Elt.getOpcode() != ISD::Constant &&
5952         Elt.getOpcode() != ISD::ConstantFP)
5953       IsAllConstants = false;
5954     if (X86::isZeroNode(Elt))
5955       NumZero++;
5956     else {
5957       NonZeros |= (1 << i);
5958       NumNonZero++;
5959     }
5960   }
5961
5962   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5963   if (NumNonZero == 0)
5964     return DAG.getUNDEF(VT);
5965
5966   // Special case for single non-zero, non-undef, element.
5967   if (NumNonZero == 1) {
5968     unsigned Idx = countTrailingZeros(NonZeros);
5969     SDValue Item = Op.getOperand(Idx);
5970
5971     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5972     // the value are obviously zero, truncate the value to i32 and do the
5973     // insertion that way.  Only do this if the value is non-constant or if the
5974     // value is a constant being inserted into element 0.  It is cheaper to do
5975     // a constant pool load than it is to do a movd + shuffle.
5976     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5977         (!IsAllConstants || Idx == 0)) {
5978       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5979         // Handle SSE only.
5980         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5981         EVT VecVT = MVT::v4i32;
5982
5983         // Truncate the value (which may itself be a constant) to i32, and
5984         // convert it to a vector with movd (S2V+shuffle to zero extend).
5985         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5986         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5987         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5988                                       Item, Idx * 2, true, Subtarget, DAG));
5989       }
5990     }
5991
5992     // If we have a constant or non-constant insertion into the low element of
5993     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5994     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5995     // depending on what the source datatype is.
5996     if (Idx == 0) {
5997       if (NumZero == 0)
5998         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5999
6000       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6001           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6002         if (VT.is512BitVector()) {
6003           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6004           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6005                              Item, DAG.getIntPtrConstant(0, dl));
6006         }
6007         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6008                "Expected an SSE value type!");
6009         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6010         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6011         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6012       }
6013
6014       // We can't directly insert an i8 or i16 into a vector, so zero extend
6015       // it to i32 first.
6016       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6017         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6018         if (VT.is256BitVector()) {
6019           if (Subtarget->hasAVX()) {
6020             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6021             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6022           } else {
6023             // Without AVX, we need to extend to a 128-bit vector and then
6024             // insert into the 256-bit vector.
6025             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6026             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6027             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6028           }
6029         } else {
6030           assert(VT.is128BitVector() && "Expected an SSE value type!");
6031           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6032           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6033         }
6034         return DAG.getBitcast(VT, Item);
6035       }
6036     }
6037
6038     // Is it a vector logical left shift?
6039     if (NumElems == 2 && Idx == 1 &&
6040         X86::isZeroNode(Op.getOperand(0)) &&
6041         !X86::isZeroNode(Op.getOperand(1))) {
6042       unsigned NumBits = VT.getSizeInBits();
6043       return getVShift(true, VT,
6044                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6045                                    VT, Op.getOperand(1)),
6046                        NumBits/2, DAG, *this, dl);
6047     }
6048
6049     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6050       return SDValue();
6051
6052     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6053     // is a non-constant being inserted into an element other than the low one,
6054     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6055     // movd/movss) to move this into the low element, then shuffle it into
6056     // place.
6057     if (EVTBits == 32) {
6058       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6059       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6060     }
6061   }
6062
6063   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6064   if (Values.size() == 1) {
6065     if (EVTBits == 32) {
6066       // Instead of a shuffle like this:
6067       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6068       // Check if it's possible to issue this instead.
6069       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6070       unsigned Idx = countTrailingZeros(NonZeros);
6071       SDValue Item = Op.getOperand(Idx);
6072       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6073         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6074     }
6075     return SDValue();
6076   }
6077
6078   // A vector full of immediates; various special cases are already
6079   // handled, so this is best done with a single constant-pool load.
6080   if (IsAllConstants)
6081     return SDValue();
6082
6083   // For AVX-length vectors, see if we can use a vector load to get all of the
6084   // elements, otherwise build the individual 128-bit pieces and use
6085   // shuffles to put them in place.
6086   if (VT.is256BitVector() || VT.is512BitVector()) {
6087     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6088
6089     // Check for a build vector of consecutive loads.
6090     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6091       return LD;
6092
6093     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6094
6095     // Build both the lower and upper subvector.
6096     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6097                                 makeArrayRef(&V[0], NumElems/2));
6098     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6099                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6100
6101     // Recreate the wider vector with the lower and upper part.
6102     if (VT.is256BitVector())
6103       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6104     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6105   }
6106
6107   // Let legalizer expand 2-wide build_vectors.
6108   if (EVTBits == 64) {
6109     if (NumNonZero == 1) {
6110       // One half is zero or undef.
6111       unsigned Idx = countTrailingZeros(NonZeros);
6112       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6113                                  Op.getOperand(Idx));
6114       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6115     }
6116     return SDValue();
6117   }
6118
6119   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6120   if (EVTBits == 8 && NumElems == 16)
6121     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6122                                         Subtarget, *this))
6123       return V;
6124
6125   if (EVTBits == 16 && NumElems == 8)
6126     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6127                                       Subtarget, *this))
6128       return V;
6129
6130   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6131   if (EVTBits == 32 && NumElems == 4)
6132     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6133       return V;
6134
6135   // If element VT is == 32 bits, turn it into a number of shuffles.
6136   SmallVector<SDValue, 8> V(NumElems);
6137   if (NumElems == 4 && NumZero > 0) {
6138     for (unsigned i = 0; i < 4; ++i) {
6139       bool isZero = !(NonZeros & (1 << i));
6140       if (isZero)
6141         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6142       else
6143         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6144     }
6145
6146     for (unsigned i = 0; i < 2; ++i) {
6147       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6148         default: break;
6149         case 0:
6150           V[i] = V[i*2];  // Must be a zero vector.
6151           break;
6152         case 1:
6153           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6154           break;
6155         case 2:
6156           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6157           break;
6158         case 3:
6159           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6160           break;
6161       }
6162     }
6163
6164     bool Reverse1 = (NonZeros & 0x3) == 2;
6165     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6166     int MaskVec[] = {
6167       Reverse1 ? 1 : 0,
6168       Reverse1 ? 0 : 1,
6169       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6170       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6171     };
6172     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6173   }
6174
6175   if (Values.size() > 1 && VT.is128BitVector()) {
6176     // Check for a build vector of consecutive loads.
6177     for (unsigned i = 0; i < NumElems; ++i)
6178       V[i] = Op.getOperand(i);
6179
6180     // Check for elements which are consecutive loads.
6181     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6182       return LD;
6183
6184     // Check for a build vector from mostly shuffle plus few inserting.
6185     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6186       return Sh;
6187
6188     // For SSE 4.1, use insertps to put the high elements into the low element.
6189     if (Subtarget->hasSSE41()) {
6190       SDValue Result;
6191       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6192         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6193       else
6194         Result = DAG.getUNDEF(VT);
6195
6196       for (unsigned i = 1; i < NumElems; ++i) {
6197         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6198         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6199                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6200       }
6201       return Result;
6202     }
6203
6204     // Otherwise, expand into a number of unpckl*, start by extending each of
6205     // our (non-undef) elements to the full vector width with the element in the
6206     // bottom slot of the vector (which generates no code for SSE).
6207     for (unsigned i = 0; i < NumElems; ++i) {
6208       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6209         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6210       else
6211         V[i] = DAG.getUNDEF(VT);
6212     }
6213
6214     // Next, we iteratively mix elements, e.g. for v4f32:
6215     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6216     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6217     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6218     unsigned EltStride = NumElems >> 1;
6219     while (EltStride != 0) {
6220       for (unsigned i = 0; i < EltStride; ++i) {
6221         // If V[i+EltStride] is undef and this is the first round of mixing,
6222         // then it is safe to just drop this shuffle: V[i] is already in the
6223         // right place, the one element (since it's the first round) being
6224         // inserted as undef can be dropped.  This isn't safe for successive
6225         // rounds because they will permute elements within both vectors.
6226         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6227             EltStride == NumElems/2)
6228           continue;
6229
6230         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6231       }
6232       EltStride >>= 1;
6233     }
6234     return V[0];
6235   }
6236   return SDValue();
6237 }
6238
6239 // 256-bit AVX can use the vinsertf128 instruction
6240 // to create 256-bit vectors from two other 128-bit ones.
6241 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6242   SDLoc dl(Op);
6243   MVT ResVT = Op.getSimpleValueType();
6244
6245   assert((ResVT.is256BitVector() ||
6246           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6247
6248   SDValue V1 = Op.getOperand(0);
6249   SDValue V2 = Op.getOperand(1);
6250   unsigned NumElems = ResVT.getVectorNumElements();
6251   if (ResVT.is256BitVector())
6252     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6253
6254   if (Op.getNumOperands() == 4) {
6255     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6256                                 ResVT.getVectorNumElements()/2);
6257     SDValue V3 = Op.getOperand(2);
6258     SDValue V4 = Op.getOperand(3);
6259     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6260       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6261   }
6262   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6263 }
6264
6265 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6266                                        const X86Subtarget *Subtarget,
6267                                        SelectionDAG & DAG) {
6268   SDLoc dl(Op);
6269   MVT ResVT = Op.getSimpleValueType();
6270   unsigned NumOfOperands = Op.getNumOperands();
6271
6272   assert(isPowerOf2_32(NumOfOperands) &&
6273          "Unexpected number of operands in CONCAT_VECTORS");
6274
6275   if (NumOfOperands > 2) {
6276     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6277                                   ResVT.getVectorNumElements()/2);
6278     SmallVector<SDValue, 2> Ops;
6279     for (unsigned i = 0; i < NumOfOperands/2; i++)
6280       Ops.push_back(Op.getOperand(i));
6281     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6282     Ops.clear();
6283     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6284       Ops.push_back(Op.getOperand(i));
6285     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6286     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6287   }
6288
6289   SDValue V1 = Op.getOperand(0);
6290   SDValue V2 = Op.getOperand(1);
6291   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6292   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6293
6294   if (IsZeroV1 && IsZeroV2)
6295     return getZeroVector(ResVT, Subtarget, DAG, dl);
6296
6297   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6298   SDValue Undef = DAG.getUNDEF(ResVT);
6299   unsigned NumElems = ResVT.getVectorNumElements();
6300   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6301
6302   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6303   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6304   if (IsZeroV1)
6305     return V2;
6306
6307   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6308   // Zero the upper bits of V1
6309   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6310   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6311   if (IsZeroV2)
6312     return V1;
6313   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6314 }
6315
6316 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6317                                    const X86Subtarget *Subtarget,
6318                                    SelectionDAG &DAG) {
6319   MVT VT = Op.getSimpleValueType();
6320   if (VT.getVectorElementType() == MVT::i1)
6321     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6322
6323   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6324          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6325           Op.getNumOperands() == 4)));
6326
6327   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6328   // from two other 128-bit ones.
6329
6330   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6331   return LowerAVXCONCAT_VECTORS(Op, DAG);
6332 }
6333
6334
6335 //===----------------------------------------------------------------------===//
6336 // Vector shuffle lowering
6337 //
6338 // This is an experimental code path for lowering vector shuffles on x86. It is
6339 // designed to handle arbitrary vector shuffles and blends, gracefully
6340 // degrading performance as necessary. It works hard to recognize idiomatic
6341 // shuffles and lower them to optimal instruction patterns without leaving
6342 // a framework that allows reasonably efficient handling of all vector shuffle
6343 // patterns.
6344 //===----------------------------------------------------------------------===//
6345
6346 /// \brief Tiny helper function to identify a no-op mask.
6347 ///
6348 /// This is a somewhat boring predicate function. It checks whether the mask
6349 /// array input, which is assumed to be a single-input shuffle mask of the kind
6350 /// used by the X86 shuffle instructions (not a fully general
6351 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6352 /// in-place shuffle are 'no-op's.
6353 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6354   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6355     if (Mask[i] != -1 && Mask[i] != i)
6356       return false;
6357   return true;
6358 }
6359
6360 /// \brief Helper function to classify a mask as a single-input mask.
6361 ///
6362 /// This isn't a generic single-input test because in the vector shuffle
6363 /// lowering we canonicalize single inputs to be the first input operand. This
6364 /// means we can more quickly test for a single input by only checking whether
6365 /// an input from the second operand exists. We also assume that the size of
6366 /// mask corresponds to the size of the input vectors which isn't true in the
6367 /// fully general case.
6368 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6369   for (int M : Mask)
6370     if (M >= (int)Mask.size())
6371       return false;
6372   return true;
6373 }
6374
6375 /// \brief Test whether there are elements crossing 128-bit lanes in this
6376 /// shuffle mask.
6377 ///
6378 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6379 /// and we routinely test for these.
6380 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6381   int LaneSize = 128 / VT.getScalarSizeInBits();
6382   int Size = Mask.size();
6383   for (int i = 0; i < Size; ++i)
6384     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6385       return true;
6386   return false;
6387 }
6388
6389 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6390 ///
6391 /// This checks a shuffle mask to see if it is performing the same
6392 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6393 /// that it is also not lane-crossing. It may however involve a blend from the
6394 /// same lane of a second vector.
6395 ///
6396 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6397 /// non-trivial to compute in the face of undef lanes. The representation is
6398 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6399 /// entries from both V1 and V2 inputs to the wider mask.
6400 static bool
6401 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6402                                 SmallVectorImpl<int> &RepeatedMask) {
6403   int LaneSize = 128 / VT.getScalarSizeInBits();
6404   RepeatedMask.resize(LaneSize, -1);
6405   int Size = Mask.size();
6406   for (int i = 0; i < Size; ++i) {
6407     if (Mask[i] < 0)
6408       continue;
6409     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6410       // This entry crosses lanes, so there is no way to model this shuffle.
6411       return false;
6412
6413     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6414     if (RepeatedMask[i % LaneSize] == -1)
6415       // This is the first non-undef entry in this slot of a 128-bit lane.
6416       RepeatedMask[i % LaneSize] =
6417           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6418     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6419       // Found a mismatch with the repeated mask.
6420       return false;
6421   }
6422   return true;
6423 }
6424
6425 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6426 /// arguments.
6427 ///
6428 /// This is a fast way to test a shuffle mask against a fixed pattern:
6429 ///
6430 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6431 ///
6432 /// It returns true if the mask is exactly as wide as the argument list, and
6433 /// each element of the mask is either -1 (signifying undef) or the value given
6434 /// in the argument.
6435 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6436                                 ArrayRef<int> ExpectedMask) {
6437   if (Mask.size() != ExpectedMask.size())
6438     return false;
6439
6440   int Size = Mask.size();
6441
6442   // If the values are build vectors, we can look through them to find
6443   // equivalent inputs that make the shuffles equivalent.
6444   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6445   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6446
6447   for (int i = 0; i < Size; ++i)
6448     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6449       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6450       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6451       if (!MaskBV || !ExpectedBV ||
6452           MaskBV->getOperand(Mask[i] % Size) !=
6453               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6454         return false;
6455     }
6456
6457   return true;
6458 }
6459
6460 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6461 ///
6462 /// This helper function produces an 8-bit shuffle immediate corresponding to
6463 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6464 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6465 /// example.
6466 ///
6467 /// NB: We rely heavily on "undef" masks preserving the input lane.
6468 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6469                                           SelectionDAG &DAG) {
6470   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6471   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6472   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6473   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6474   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6475
6476   unsigned Imm = 0;
6477   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6478   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6479   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6480   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6481   return DAG.getConstant(Imm, DL, MVT::i8);
6482 }
6483
6484 /// \brief Compute whether each element of a shuffle is zeroable.
6485 ///
6486 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6487 /// Either it is an undef element in the shuffle mask, the element of the input
6488 /// referenced is undef, or the element of the input referenced is known to be
6489 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6490 /// as many lanes with this technique as possible to simplify the remaining
6491 /// shuffle.
6492 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6493                                                      SDValue V1, SDValue V2) {
6494   SmallBitVector Zeroable(Mask.size(), false);
6495
6496   while (V1.getOpcode() == ISD::BITCAST)
6497     V1 = V1->getOperand(0);
6498   while (V2.getOpcode() == ISD::BITCAST)
6499     V2 = V2->getOperand(0);
6500
6501   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6502   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6503
6504   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6505     int M = Mask[i];
6506     // Handle the easy cases.
6507     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6508       Zeroable[i] = true;
6509       continue;
6510     }
6511
6512     // If this is an index into a build_vector node (which has the same number
6513     // of elements), dig out the input value and use it.
6514     SDValue V = M < Size ? V1 : V2;
6515     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6516       continue;
6517
6518     SDValue Input = V.getOperand(M % Size);
6519     // The UNDEF opcode check really should be dead code here, but not quite
6520     // worth asserting on (it isn't invalid, just unexpected).
6521     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6522       Zeroable[i] = true;
6523   }
6524
6525   return Zeroable;
6526 }
6527
6528 /// \brief Try to emit a bitmask instruction for a shuffle.
6529 ///
6530 /// This handles cases where we can model a blend exactly as a bitmask due to
6531 /// one of the inputs being zeroable.
6532 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6533                                            SDValue V2, ArrayRef<int> Mask,
6534                                            SelectionDAG &DAG) {
6535   MVT EltVT = VT.getScalarType();
6536   int NumEltBits = EltVT.getSizeInBits();
6537   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6538   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6539   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6540                                     IntEltVT);
6541   if (EltVT.isFloatingPoint()) {
6542     Zero = DAG.getBitcast(EltVT, Zero);
6543     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6544   }
6545   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6546   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6547   SDValue V;
6548   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6549     if (Zeroable[i])
6550       continue;
6551     if (Mask[i] % Size != i)
6552       return SDValue(); // Not a blend.
6553     if (!V)
6554       V = Mask[i] < Size ? V1 : V2;
6555     else if (V != (Mask[i] < Size ? V1 : V2))
6556       return SDValue(); // Can only let one input through the mask.
6557
6558     VMaskOps[i] = AllOnes;
6559   }
6560   if (!V)
6561     return SDValue(); // No non-zeroable elements!
6562
6563   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6564   V = DAG.getNode(VT.isFloatingPoint()
6565                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6566                   DL, VT, V, VMask);
6567   return V;
6568 }
6569
6570 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6571 ///
6572 /// This is used as a fallback approach when first class blend instructions are
6573 /// unavailable. Currently it is only suitable for integer vectors, but could
6574 /// be generalized for floating point vectors if desirable.
6575 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6576                                             SDValue V2, ArrayRef<int> Mask,
6577                                             SelectionDAG &DAG) {
6578   assert(VT.isInteger() && "Only supports integer vector types!");
6579   MVT EltVT = VT.getScalarType();
6580   int NumEltBits = EltVT.getSizeInBits();
6581   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6582   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6583                                     EltVT);
6584   SmallVector<SDValue, 16> MaskOps;
6585   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6586     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6587       return SDValue(); // Shuffled input!
6588     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6589   }
6590
6591   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6592   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6593   // We have to cast V2 around.
6594   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6595   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6596                                       DAG.getBitcast(MaskVT, V1Mask),
6597                                       DAG.getBitcast(MaskVT, V2)));
6598   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6599 }
6600
6601 /// \brief Try to emit a blend instruction for a shuffle.
6602 ///
6603 /// This doesn't do any checks for the availability of instructions for blending
6604 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6605 /// be matched in the backend with the type given. What it does check for is
6606 /// that the shuffle mask is in fact a blend.
6607 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6608                                          SDValue V2, ArrayRef<int> Mask,
6609                                          const X86Subtarget *Subtarget,
6610                                          SelectionDAG &DAG) {
6611   unsigned BlendMask = 0;
6612   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6613     if (Mask[i] >= Size) {
6614       if (Mask[i] != i + Size)
6615         return SDValue(); // Shuffled V2 input!
6616       BlendMask |= 1u << i;
6617       continue;
6618     }
6619     if (Mask[i] >= 0 && Mask[i] != i)
6620       return SDValue(); // Shuffled V1 input!
6621   }
6622   switch (VT.SimpleTy) {
6623   case MVT::v2f64:
6624   case MVT::v4f32:
6625   case MVT::v4f64:
6626   case MVT::v8f32:
6627     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6628                        DAG.getConstant(BlendMask, DL, MVT::i8));
6629
6630   case MVT::v4i64:
6631   case MVT::v8i32:
6632     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6633     // FALLTHROUGH
6634   case MVT::v2i64:
6635   case MVT::v4i32:
6636     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6637     // that instruction.
6638     if (Subtarget->hasAVX2()) {
6639       // Scale the blend by the number of 32-bit dwords per element.
6640       int Scale =  VT.getScalarSizeInBits() / 32;
6641       BlendMask = 0;
6642       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6643         if (Mask[i] >= Size)
6644           for (int j = 0; j < Scale; ++j)
6645             BlendMask |= 1u << (i * Scale + j);
6646
6647       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6648       V1 = DAG.getBitcast(BlendVT, V1);
6649       V2 = DAG.getBitcast(BlendVT, V2);
6650       return DAG.getBitcast(
6651           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6652                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6653     }
6654     // FALLTHROUGH
6655   case MVT::v8i16: {
6656     // For integer shuffles we need to expand the mask and cast the inputs to
6657     // v8i16s prior to blending.
6658     int Scale = 8 / VT.getVectorNumElements();
6659     BlendMask = 0;
6660     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6661       if (Mask[i] >= Size)
6662         for (int j = 0; j < Scale; ++j)
6663           BlendMask |= 1u << (i * Scale + j);
6664
6665     V1 = DAG.getBitcast(MVT::v8i16, V1);
6666     V2 = DAG.getBitcast(MVT::v8i16, V2);
6667     return DAG.getBitcast(VT,
6668                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6669                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6670   }
6671
6672   case MVT::v16i16: {
6673     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6674     SmallVector<int, 8> RepeatedMask;
6675     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6676       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6677       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6678       BlendMask = 0;
6679       for (int i = 0; i < 8; ++i)
6680         if (RepeatedMask[i] >= 16)
6681           BlendMask |= 1u << i;
6682       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6683                          DAG.getConstant(BlendMask, DL, MVT::i8));
6684     }
6685   }
6686     // FALLTHROUGH
6687   case MVT::v16i8:
6688   case MVT::v32i8: {
6689     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6690            "256-bit byte-blends require AVX2 support!");
6691
6692     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6693     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6694       return Masked;
6695
6696     // Scale the blend by the number of bytes per element.
6697     int Scale = VT.getScalarSizeInBits() / 8;
6698
6699     // This form of blend is always done on bytes. Compute the byte vector
6700     // type.
6701     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6702
6703     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6704     // mix of LLVM's code generator and the x86 backend. We tell the code
6705     // generator that boolean values in the elements of an x86 vector register
6706     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6707     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6708     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6709     // of the element (the remaining are ignored) and 0 in that high bit would
6710     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6711     // the LLVM model for boolean values in vector elements gets the relevant
6712     // bit set, it is set backwards and over constrained relative to x86's
6713     // actual model.
6714     SmallVector<SDValue, 32> VSELECTMask;
6715     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6716       for (int j = 0; j < Scale; ++j)
6717         VSELECTMask.push_back(
6718             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6719                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6720                                           MVT::i8));
6721
6722     V1 = DAG.getBitcast(BlendVT, V1);
6723     V2 = DAG.getBitcast(BlendVT, V2);
6724     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6725                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6726                                                       BlendVT, VSELECTMask),
6727                                           V1, V2));
6728   }
6729
6730   default:
6731     llvm_unreachable("Not a supported integer vector type!");
6732   }
6733 }
6734
6735 /// \brief Try to lower as a blend of elements from two inputs followed by
6736 /// a single-input permutation.
6737 ///
6738 /// This matches the pattern where we can blend elements from two inputs and
6739 /// then reduce the shuffle to a single-input permutation.
6740 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6741                                                    SDValue V2,
6742                                                    ArrayRef<int> Mask,
6743                                                    SelectionDAG &DAG) {
6744   // We build up the blend mask while checking whether a blend is a viable way
6745   // to reduce the shuffle.
6746   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6747   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6748
6749   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6750     if (Mask[i] < 0)
6751       continue;
6752
6753     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6754
6755     if (BlendMask[Mask[i] % Size] == -1)
6756       BlendMask[Mask[i] % Size] = Mask[i];
6757     else if (BlendMask[Mask[i] % Size] != Mask[i])
6758       return SDValue(); // Can't blend in the needed input!
6759
6760     PermuteMask[i] = Mask[i] % Size;
6761   }
6762
6763   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6764   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6765 }
6766
6767 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6768 /// blends and permutes.
6769 ///
6770 /// This matches the extremely common pattern for handling combined
6771 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6772 /// operations. It will try to pick the best arrangement of shuffles and
6773 /// blends.
6774 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6775                                                           SDValue V1,
6776                                                           SDValue V2,
6777                                                           ArrayRef<int> Mask,
6778                                                           SelectionDAG &DAG) {
6779   // Shuffle the input elements into the desired positions in V1 and V2 and
6780   // blend them together.
6781   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6782   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6783   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6784   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6785     if (Mask[i] >= 0 && Mask[i] < Size) {
6786       V1Mask[i] = Mask[i];
6787       BlendMask[i] = i;
6788     } else if (Mask[i] >= Size) {
6789       V2Mask[i] = Mask[i] - Size;
6790       BlendMask[i] = i + Size;
6791     }
6792
6793   // Try to lower with the simpler initial blend strategy unless one of the
6794   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6795   // shuffle may be able to fold with a load or other benefit. However, when
6796   // we'll have to do 2x as many shuffles in order to achieve this, blending
6797   // first is a better strategy.
6798   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6799     if (SDValue BlendPerm =
6800             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6801       return BlendPerm;
6802
6803   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6804   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6805   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6806 }
6807
6808 /// \brief Try to lower a vector shuffle as a byte rotation.
6809 ///
6810 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6811 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6812 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6813 /// try to generically lower a vector shuffle through such an pattern. It
6814 /// does not check for the profitability of lowering either as PALIGNR or
6815 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6816 /// This matches shuffle vectors that look like:
6817 ///
6818 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6819 ///
6820 /// Essentially it concatenates V1 and V2, shifts right by some number of
6821 /// elements, and takes the low elements as the result. Note that while this is
6822 /// specified as a *right shift* because x86 is little-endian, it is a *left
6823 /// rotate* of the vector lanes.
6824 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6825                                               SDValue V2,
6826                                               ArrayRef<int> Mask,
6827                                               const X86Subtarget *Subtarget,
6828                                               SelectionDAG &DAG) {
6829   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6830
6831   int NumElts = Mask.size();
6832   int NumLanes = VT.getSizeInBits() / 128;
6833   int NumLaneElts = NumElts / NumLanes;
6834
6835   // We need to detect various ways of spelling a rotation:
6836   //   [11, 12, 13, 14, 15,  0,  1,  2]
6837   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6838   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6839   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6840   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6841   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6842   int Rotation = 0;
6843   SDValue Lo, Hi;
6844   for (int l = 0; l < NumElts; l += NumLaneElts) {
6845     for (int i = 0; i < NumLaneElts; ++i) {
6846       if (Mask[l + i] == -1)
6847         continue;
6848       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6849
6850       // Get the mod-Size index and lane correct it.
6851       int LaneIdx = (Mask[l + i] % NumElts) - l;
6852       // Make sure it was in this lane.
6853       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6854         return SDValue();
6855
6856       // Determine where a rotated vector would have started.
6857       int StartIdx = i - LaneIdx;
6858       if (StartIdx == 0)
6859         // The identity rotation isn't interesting, stop.
6860         return SDValue();
6861
6862       // If we found the tail of a vector the rotation must be the missing
6863       // front. If we found the head of a vector, it must be how much of the
6864       // head.
6865       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6866
6867       if (Rotation == 0)
6868         Rotation = CandidateRotation;
6869       else if (Rotation != CandidateRotation)
6870         // The rotations don't match, so we can't match this mask.
6871         return SDValue();
6872
6873       // Compute which value this mask is pointing at.
6874       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6875
6876       // Compute which of the two target values this index should be assigned
6877       // to. This reflects whether the high elements are remaining or the low
6878       // elements are remaining.
6879       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6880
6881       // Either set up this value if we've not encountered it before, or check
6882       // that it remains consistent.
6883       if (!TargetV)
6884         TargetV = MaskV;
6885       else if (TargetV != MaskV)
6886         // This may be a rotation, but it pulls from the inputs in some
6887         // unsupported interleaving.
6888         return SDValue();
6889     }
6890   }
6891
6892   // Check that we successfully analyzed the mask, and normalize the results.
6893   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6894   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6895   if (!Lo)
6896     Lo = Hi;
6897   else if (!Hi)
6898     Hi = Lo;
6899
6900   // The actual rotate instruction rotates bytes, so we need to scale the
6901   // rotation based on how many bytes are in the vector lane.
6902   int Scale = 16 / NumLaneElts;
6903
6904   // SSSE3 targets can use the palignr instruction.
6905   if (Subtarget->hasSSSE3()) {
6906     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6907     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6908     Lo = DAG.getBitcast(AlignVT, Lo);
6909     Hi = DAG.getBitcast(AlignVT, Hi);
6910
6911     return DAG.getBitcast(
6912         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6913                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6914   }
6915
6916   assert(VT.getSizeInBits() == 128 &&
6917          "Rotate-based lowering only supports 128-bit lowering!");
6918   assert(Mask.size() <= 16 &&
6919          "Can shuffle at most 16 bytes in a 128-bit vector!");
6920
6921   // Default SSE2 implementation
6922   int LoByteShift = 16 - Rotation * Scale;
6923   int HiByteShift = Rotation * Scale;
6924
6925   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6926   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6927   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6928
6929   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6930                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6931   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6932                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6933   return DAG.getBitcast(VT,
6934                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6935 }
6936
6937 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6938 ///
6939 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6940 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6941 /// matches elements from one of the input vectors shuffled to the left or
6942 /// right with zeroable elements 'shifted in'. It handles both the strictly
6943 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6944 /// quad word lane.
6945 ///
6946 /// PSHL : (little-endian) left bit shift.
6947 /// [ zz, 0, zz,  2 ]
6948 /// [ -1, 4, zz, -1 ]
6949 /// PSRL : (little-endian) right bit shift.
6950 /// [  1, zz,  3, zz]
6951 /// [ -1, -1,  7, zz]
6952 /// PSLLDQ : (little-endian) left byte shift
6953 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6954 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6955 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6956 /// PSRLDQ : (little-endian) right byte shift
6957 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6958 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6959 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6960 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6961                                          SDValue V2, ArrayRef<int> Mask,
6962                                          SelectionDAG &DAG) {
6963   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6964
6965   int Size = Mask.size();
6966   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6967
6968   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6969     for (int i = 0; i < Size; i += Scale)
6970       for (int j = 0; j < Shift; ++j)
6971         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6972           return false;
6973
6974     return true;
6975   };
6976
6977   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6978     for (int i = 0; i != Size; i += Scale) {
6979       unsigned Pos = Left ? i + Shift : i;
6980       unsigned Low = Left ? i : i + Shift;
6981       unsigned Len = Scale - Shift;
6982       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6983                                       Low + (V == V1 ? 0 : Size)))
6984         return SDValue();
6985     }
6986
6987     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6988     bool ByteShift = ShiftEltBits > 64;
6989     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6990                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6991     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6992
6993     // Normalize the scale for byte shifts to still produce an i64 element
6994     // type.
6995     Scale = ByteShift ? Scale / 2 : Scale;
6996
6997     // We need to round trip through the appropriate type for the shift.
6998     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6999     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7000     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7001            "Illegal integer vector type");
7002     V = DAG.getBitcast(ShiftVT, V);
7003
7004     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7005                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7006     return DAG.getBitcast(VT, V);
7007   };
7008
7009   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7010   // keep doubling the size of the integer elements up to that. We can
7011   // then shift the elements of the integer vector by whole multiples of
7012   // their width within the elements of the larger integer vector. Test each
7013   // multiple to see if we can find a match with the moved element indices
7014   // and that the shifted in elements are all zeroable.
7015   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7016     for (int Shift = 1; Shift != Scale; ++Shift)
7017       for (bool Left : {true, false})
7018         if (CheckZeros(Shift, Scale, Left))
7019           for (SDValue V : {V1, V2})
7020             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7021               return Match;
7022
7023   // no match
7024   return SDValue();
7025 }
7026
7027 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7028 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7029                                            SDValue V2, ArrayRef<int> Mask,
7030                                            SelectionDAG &DAG) {
7031   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7032   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7033
7034   int Size = Mask.size();
7035   int HalfSize = Size / 2;
7036   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7037
7038   // Upper half must be undefined.
7039   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7040     return SDValue();
7041
7042   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7043   // Remainder of lower half result is zero and upper half is all undef.
7044   auto LowerAsEXTRQ = [&]() {
7045     // Determine the extraction length from the part of the
7046     // lower half that isn't zeroable.
7047     int Len = HalfSize;
7048     for (; Len >= 0; --Len)
7049       if (!Zeroable[Len - 1])
7050         break;
7051     assert(Len > 0 && "Zeroable shuffle mask");
7052
7053     // Attempt to match first Len sequential elements from the lower half.
7054     SDValue Src;
7055     int Idx = -1;
7056     for (int i = 0; i != Len; ++i) {
7057       int M = Mask[i];
7058       if (M < 0)
7059         continue;
7060       SDValue &V = (M < Size ? V1 : V2);
7061       M = M % Size;
7062
7063       // All mask elements must be in the lower half.
7064       if (M > HalfSize)
7065         return SDValue();
7066
7067       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7068         Src = V;
7069         Idx = M - i;
7070         continue;
7071       }
7072       return SDValue();
7073     }
7074
7075     if (Idx < 0)
7076       return SDValue();
7077
7078     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7079     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7080     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7081     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7082                        DAG.getConstant(BitLen, DL, MVT::i8),
7083                        DAG.getConstant(BitIdx, DL, MVT::i8));
7084   };
7085
7086   if (SDValue ExtrQ = LowerAsEXTRQ())
7087     return ExtrQ;
7088
7089   // INSERTQ: Extract lowest Len elements from lower half of second source and
7090   // insert over first source, starting at Idx.
7091   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7092   auto LowerAsInsertQ = [&]() {
7093     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7094       SDValue Base;
7095
7096       // Attempt to match first source from mask before insertion point.
7097       if (isUndefInRange(Mask, 0, Idx)) {
7098         /* EMPTY */
7099       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7100         Base = V1;
7101       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7102         Base = V2;
7103       } else {
7104         continue;
7105       }
7106
7107       // Extend the extraction length looking to match both the insertion of
7108       // the second source and the remaining elements of the first.
7109       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7110         SDValue Insert;
7111         int Len = Hi - Idx;
7112
7113         // Match insertion.
7114         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7115           Insert = V1;
7116         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7117           Insert = V2;
7118         } else {
7119           continue;
7120         }
7121
7122         // Match the remaining elements of the lower half.
7123         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7124           /* EMPTY */
7125         } else if ((!Base || (Base == V1)) &&
7126                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7127           Base = V1;
7128         } else if ((!Base || (Base == V2)) &&
7129                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7130                                               Size + Hi)) {
7131           Base = V2;
7132         } else {
7133           continue;
7134         }
7135
7136         // We may not have a base (first source) - this can safely be undefined.
7137         if (!Base)
7138           Base = DAG.getUNDEF(VT);
7139
7140         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7141         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7142         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7143                            DAG.getConstant(BitLen, DL, MVT::i8),
7144                            DAG.getConstant(BitIdx, DL, MVT::i8));
7145       }
7146     }
7147
7148     return SDValue();
7149   };
7150
7151   if (SDValue InsertQ = LowerAsInsertQ())
7152     return InsertQ;
7153
7154   return SDValue();
7155 }
7156
7157 /// \brief Lower a vector shuffle as a zero or any extension.
7158 ///
7159 /// Given a specific number of elements, element bit width, and extension
7160 /// stride, produce either a zero or any extension based on the available
7161 /// features of the subtarget.
7162 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7163     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7164     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7165   assert(Scale > 1 && "Need a scale to extend.");
7166   int NumElements = VT.getVectorNumElements();
7167   int EltBits = VT.getScalarSizeInBits();
7168   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7169          "Only 8, 16, and 32 bit elements can be extended.");
7170   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7171
7172   // Found a valid zext mask! Try various lowering strategies based on the
7173   // input type and available ISA extensions.
7174   if (Subtarget->hasSSE41()) {
7175     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7176                                  NumElements / Scale);
7177     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7178   }
7179
7180   // For any extends we can cheat for larger element sizes and use shuffle
7181   // instructions that can fold with a load and/or copy.
7182   if (AnyExt && EltBits == 32) {
7183     int PSHUFDMask[4] = {0, -1, 1, -1};
7184     return DAG.getBitcast(
7185         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7186                         DAG.getBitcast(MVT::v4i32, InputV),
7187                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7188   }
7189   if (AnyExt && EltBits == 16 && Scale > 2) {
7190     int PSHUFDMask[4] = {0, -1, 0, -1};
7191     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7192                          DAG.getBitcast(MVT::v4i32, InputV),
7193                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7194     int PSHUFHWMask[4] = {1, -1, -1, -1};
7195     return DAG.getBitcast(
7196         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7197                         DAG.getBitcast(MVT::v8i16, InputV),
7198                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7199   }
7200
7201   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7202   // to 64-bits.
7203   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7204     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7205     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7206
7207     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7208                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7209                                          DAG.getConstant(EltBits, DL, MVT::i8),
7210                                          DAG.getConstant(0, DL, MVT::i8)));
7211     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7212       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7213
7214     SDValue Hi =
7215         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7216                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7217                                 DAG.getConstant(EltBits, DL, MVT::i8),
7218                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7219     return DAG.getNode(ISD::BITCAST, DL, VT,
7220                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7221   }
7222
7223   // If this would require more than 2 unpack instructions to expand, use
7224   // pshufb when available. We can only use more than 2 unpack instructions
7225   // when zero extending i8 elements which also makes it easier to use pshufb.
7226   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7227     assert(NumElements == 16 && "Unexpected byte vector width!");
7228     SDValue PSHUFBMask[16];
7229     for (int i = 0; i < 16; ++i)
7230       PSHUFBMask[i] =
7231           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7232     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7233     return DAG.getBitcast(VT,
7234                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7235                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7236                                                   MVT::v16i8, PSHUFBMask)));
7237   }
7238
7239   // Otherwise emit a sequence of unpacks.
7240   do {
7241     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7242     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7243                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7244     InputV = DAG.getBitcast(InputVT, InputV);
7245     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7246     Scale /= 2;
7247     EltBits *= 2;
7248     NumElements /= 2;
7249   } while (Scale > 1);
7250   return DAG.getBitcast(VT, InputV);
7251 }
7252
7253 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7254 ///
7255 /// This routine will try to do everything in its power to cleverly lower
7256 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7257 /// check for the profitability of this lowering,  it tries to aggressively
7258 /// match this pattern. It will use all of the micro-architectural details it
7259 /// can to emit an efficient lowering. It handles both blends with all-zero
7260 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7261 /// masking out later).
7262 ///
7263 /// The reason we have dedicated lowering for zext-style shuffles is that they
7264 /// are both incredibly common and often quite performance sensitive.
7265 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7266     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7267     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7268   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7269
7270   int Bits = VT.getSizeInBits();
7271   int NumElements = VT.getVectorNumElements();
7272   assert(VT.getScalarSizeInBits() <= 32 &&
7273          "Exceeds 32-bit integer zero extension limit");
7274   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7275
7276   // Define a helper function to check a particular ext-scale and lower to it if
7277   // valid.
7278   auto Lower = [&](int Scale) -> SDValue {
7279     SDValue InputV;
7280     bool AnyExt = true;
7281     for (int i = 0; i < NumElements; ++i) {
7282       if (Mask[i] == -1)
7283         continue; // Valid anywhere but doesn't tell us anything.
7284       if (i % Scale != 0) {
7285         // Each of the extended elements need to be zeroable.
7286         if (!Zeroable[i])
7287           return SDValue();
7288
7289         // We no longer are in the anyext case.
7290         AnyExt = false;
7291         continue;
7292       }
7293
7294       // Each of the base elements needs to be consecutive indices into the
7295       // same input vector.
7296       SDValue V = Mask[i] < NumElements ? V1 : V2;
7297       if (!InputV)
7298         InputV = V;
7299       else if (InputV != V)
7300         return SDValue(); // Flip-flopping inputs.
7301
7302       if (Mask[i] % NumElements != i / Scale)
7303         return SDValue(); // Non-consecutive strided elements.
7304     }
7305
7306     // If we fail to find an input, we have a zero-shuffle which should always
7307     // have already been handled.
7308     // FIXME: Maybe handle this here in case during blending we end up with one?
7309     if (!InputV)
7310       return SDValue();
7311
7312     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7313         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7314   };
7315
7316   // The widest scale possible for extending is to a 64-bit integer.
7317   assert(Bits % 64 == 0 &&
7318          "The number of bits in a vector must be divisible by 64 on x86!");
7319   int NumExtElements = Bits / 64;
7320
7321   // Each iteration, try extending the elements half as much, but into twice as
7322   // many elements.
7323   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7324     assert(NumElements % NumExtElements == 0 &&
7325            "The input vector size must be divisible by the extended size.");
7326     if (SDValue V = Lower(NumElements / NumExtElements))
7327       return V;
7328   }
7329
7330   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7331   if (Bits != 128)
7332     return SDValue();
7333
7334   // Returns one of the source operands if the shuffle can be reduced to a
7335   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7336   auto CanZExtLowHalf = [&]() {
7337     for (int i = NumElements / 2; i != NumElements; ++i)
7338       if (!Zeroable[i])
7339         return SDValue();
7340     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7341       return V1;
7342     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7343       return V2;
7344     return SDValue();
7345   };
7346
7347   if (SDValue V = CanZExtLowHalf()) {
7348     V = DAG.getBitcast(MVT::v2i64, V);
7349     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7350     return DAG.getBitcast(VT, V);
7351   }
7352
7353   // No viable ext lowering found.
7354   return SDValue();
7355 }
7356
7357 /// \brief Try to get a scalar value for a specific element of a vector.
7358 ///
7359 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7360 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7361                                               SelectionDAG &DAG) {
7362   MVT VT = V.getSimpleValueType();
7363   MVT EltVT = VT.getVectorElementType();
7364   while (V.getOpcode() == ISD::BITCAST)
7365     V = V.getOperand(0);
7366   // If the bitcasts shift the element size, we can't extract an equivalent
7367   // element from it.
7368   MVT NewVT = V.getSimpleValueType();
7369   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7370     return SDValue();
7371
7372   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7373       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7374     // Ensure the scalar operand is the same size as the destination.
7375     // FIXME: Add support for scalar truncation where possible.
7376     SDValue S = V.getOperand(Idx);
7377     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7378       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7379   }
7380
7381   return SDValue();
7382 }
7383
7384 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7385 ///
7386 /// This is particularly important because the set of instructions varies
7387 /// significantly based on whether the operand is a load or not.
7388 static bool isShuffleFoldableLoad(SDValue V) {
7389   while (V.getOpcode() == ISD::BITCAST)
7390     V = V.getOperand(0);
7391
7392   return ISD::isNON_EXTLoad(V.getNode());
7393 }
7394
7395 /// \brief Try to lower insertion of a single element into a zero vector.
7396 ///
7397 /// This is a common pattern that we have especially efficient patterns to lower
7398 /// across all subtarget feature sets.
7399 static SDValue lowerVectorShuffleAsElementInsertion(
7400     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7401     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7402   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7403   MVT ExtVT = VT;
7404   MVT EltVT = VT.getVectorElementType();
7405
7406   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7407                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7408                 Mask.begin();
7409   bool IsV1Zeroable = true;
7410   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7411     if (i != V2Index && !Zeroable[i]) {
7412       IsV1Zeroable = false;
7413       break;
7414     }
7415
7416   // Check for a single input from a SCALAR_TO_VECTOR node.
7417   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7418   // all the smarts here sunk into that routine. However, the current
7419   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7420   // vector shuffle lowering is dead.
7421   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7422                                                DAG);
7423   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7424     // We need to zext the scalar if it is smaller than an i32.
7425     V2S = DAG.getBitcast(EltVT, V2S);
7426     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7427       // Using zext to expand a narrow element won't work for non-zero
7428       // insertions.
7429       if (!IsV1Zeroable)
7430         return SDValue();
7431
7432       // Zero-extend directly to i32.
7433       ExtVT = MVT::v4i32;
7434       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7435     }
7436     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7437   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7438              EltVT == MVT::i16) {
7439     // Either not inserting from the low element of the input or the input
7440     // element size is too small to use VZEXT_MOVL to clear the high bits.
7441     return SDValue();
7442   }
7443
7444   if (!IsV1Zeroable) {
7445     // If V1 can't be treated as a zero vector we have fewer options to lower
7446     // this. We can't support integer vectors or non-zero targets cheaply, and
7447     // the V1 elements can't be permuted in any way.
7448     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7449     if (!VT.isFloatingPoint() || V2Index != 0)
7450       return SDValue();
7451     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7452     V1Mask[V2Index] = -1;
7453     if (!isNoopShuffleMask(V1Mask))
7454       return SDValue();
7455     // This is essentially a special case blend operation, but if we have
7456     // general purpose blend operations, they are always faster. Bail and let
7457     // the rest of the lowering handle these as blends.
7458     if (Subtarget->hasSSE41())
7459       return SDValue();
7460
7461     // Otherwise, use MOVSD or MOVSS.
7462     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7463            "Only two types of floating point element types to handle!");
7464     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7465                        ExtVT, V1, V2);
7466   }
7467
7468   // This lowering only works for the low element with floating point vectors.
7469   if (VT.isFloatingPoint() && V2Index != 0)
7470     return SDValue();
7471
7472   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7473   if (ExtVT != VT)
7474     V2 = DAG.getBitcast(VT, V2);
7475
7476   if (V2Index != 0) {
7477     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7478     // the desired position. Otherwise it is more efficient to do a vector
7479     // shift left. We know that we can do a vector shift left because all
7480     // the inputs are zero.
7481     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7482       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7483       V2Shuffle[V2Index] = 0;
7484       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7485     } else {
7486       V2 = DAG.getBitcast(MVT::v2i64, V2);
7487       V2 = DAG.getNode(
7488           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7489           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7490                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7491                               DAG.getDataLayout(), VT)));
7492       V2 = DAG.getBitcast(VT, V2);
7493     }
7494   }
7495   return V2;
7496 }
7497
7498 /// \brief Try to lower broadcast of a single element.
7499 ///
7500 /// For convenience, this code also bundles all of the subtarget feature set
7501 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7502 /// a convenient way to factor it out.
7503 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7504                                              ArrayRef<int> Mask,
7505                                              const X86Subtarget *Subtarget,
7506                                              SelectionDAG &DAG) {
7507   if (!Subtarget->hasAVX())
7508     return SDValue();
7509   if (VT.isInteger() && !Subtarget->hasAVX2())
7510     return SDValue();
7511
7512   // Check that the mask is a broadcast.
7513   int BroadcastIdx = -1;
7514   for (int M : Mask)
7515     if (M >= 0 && BroadcastIdx == -1)
7516       BroadcastIdx = M;
7517     else if (M >= 0 && M != BroadcastIdx)
7518       return SDValue();
7519
7520   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7521                                             "a sorted mask where the broadcast "
7522                                             "comes from V1.");
7523
7524   // Go up the chain of (vector) values to find a scalar load that we can
7525   // combine with the broadcast.
7526   for (;;) {
7527     switch (V.getOpcode()) {
7528     case ISD::CONCAT_VECTORS: {
7529       int OperandSize = Mask.size() / V.getNumOperands();
7530       V = V.getOperand(BroadcastIdx / OperandSize);
7531       BroadcastIdx %= OperandSize;
7532       continue;
7533     }
7534
7535     case ISD::INSERT_SUBVECTOR: {
7536       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7537       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7538       if (!ConstantIdx)
7539         break;
7540
7541       int BeginIdx = (int)ConstantIdx->getZExtValue();
7542       int EndIdx =
7543           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7544       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7545         BroadcastIdx -= BeginIdx;
7546         V = VInner;
7547       } else {
7548         V = VOuter;
7549       }
7550       continue;
7551     }
7552     }
7553     break;
7554   }
7555
7556   // Check if this is a broadcast of a scalar. We special case lowering
7557   // for scalars so that we can more effectively fold with loads.
7558   // First, look through bitcast: if the original value has a larger element
7559   // type than the shuffle, the broadcast element is in essence truncated.
7560   // Make that explicit to ease folding.
7561   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7562     EVT EltVT = VT.getVectorElementType();
7563     SDValue V0 = V.getOperand(0);
7564     EVT V0VT = V0.getValueType();
7565
7566     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7567         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7568          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7569       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7570       BroadcastIdx = 0;
7571     }
7572   }
7573
7574   // Also check the simpler case, where we can directly reuse the scalar.
7575   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7576       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7577     V = V.getOperand(BroadcastIdx);
7578
7579     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7580     // Only AVX2 has register broadcasts.
7581     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7582       return SDValue();
7583   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7584     // We can't broadcast from a vector register without AVX2, and we can only
7585     // broadcast from the zero-element of a vector register.
7586     return SDValue();
7587   }
7588
7589   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7590 }
7591
7592 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7593 // INSERTPS when the V1 elements are already in the correct locations
7594 // because otherwise we can just always use two SHUFPS instructions which
7595 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7596 // perform INSERTPS if a single V1 element is out of place and all V2
7597 // elements are zeroable.
7598 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7599                                             ArrayRef<int> Mask,
7600                                             SelectionDAG &DAG) {
7601   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7602   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7603   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7604   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7605
7606   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7607
7608   unsigned ZMask = 0;
7609   int V1DstIndex = -1;
7610   int V2DstIndex = -1;
7611   bool V1UsedInPlace = false;
7612
7613   for (int i = 0; i < 4; ++i) {
7614     // Synthesize a zero mask from the zeroable elements (includes undefs).
7615     if (Zeroable[i]) {
7616       ZMask |= 1 << i;
7617       continue;
7618     }
7619
7620     // Flag if we use any V1 inputs in place.
7621     if (i == Mask[i]) {
7622       V1UsedInPlace = true;
7623       continue;
7624     }
7625
7626     // We can only insert a single non-zeroable element.
7627     if (V1DstIndex != -1 || V2DstIndex != -1)
7628       return SDValue();
7629
7630     if (Mask[i] < 4) {
7631       // V1 input out of place for insertion.
7632       V1DstIndex = i;
7633     } else {
7634       // V2 input for insertion.
7635       V2DstIndex = i;
7636     }
7637   }
7638
7639   // Don't bother if we have no (non-zeroable) element for insertion.
7640   if (V1DstIndex == -1 && V2DstIndex == -1)
7641     return SDValue();
7642
7643   // Determine element insertion src/dst indices. The src index is from the
7644   // start of the inserted vector, not the start of the concatenated vector.
7645   unsigned V2SrcIndex = 0;
7646   if (V1DstIndex != -1) {
7647     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7648     // and don't use the original V2 at all.
7649     V2SrcIndex = Mask[V1DstIndex];
7650     V2DstIndex = V1DstIndex;
7651     V2 = V1;
7652   } else {
7653     V2SrcIndex = Mask[V2DstIndex] - 4;
7654   }
7655
7656   // If no V1 inputs are used in place, then the result is created only from
7657   // the zero mask and the V2 insertion - so remove V1 dependency.
7658   if (!V1UsedInPlace)
7659     V1 = DAG.getUNDEF(MVT::v4f32);
7660
7661   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7662   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7663
7664   // Insert the V2 element into the desired position.
7665   SDLoc DL(Op);
7666   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7667                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7668 }
7669
7670 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7671 /// UNPCK instruction.
7672 ///
7673 /// This specifically targets cases where we end up with alternating between
7674 /// the two inputs, and so can permute them into something that feeds a single
7675 /// UNPCK instruction. Note that this routine only targets integer vectors
7676 /// because for floating point vectors we have a generalized SHUFPS lowering
7677 /// strategy that handles everything that doesn't *exactly* match an unpack,
7678 /// making this clever lowering unnecessary.
7679 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7680                                           SDValue V2, ArrayRef<int> Mask,
7681                                           SelectionDAG &DAG) {
7682   assert(!VT.isFloatingPoint() &&
7683          "This routine only supports integer vectors.");
7684   assert(!isSingleInputShuffleMask(Mask) &&
7685          "This routine should only be used when blending two inputs.");
7686   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7687
7688   int Size = Mask.size();
7689
7690   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7691     return M >= 0 && M % Size < Size / 2;
7692   });
7693   int NumHiInputs = std::count_if(
7694       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7695
7696   bool UnpackLo = NumLoInputs >= NumHiInputs;
7697
7698   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7699     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7700     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7701
7702     for (int i = 0; i < Size; ++i) {
7703       if (Mask[i] < 0)
7704         continue;
7705
7706       // Each element of the unpack contains Scale elements from this mask.
7707       int UnpackIdx = i / Scale;
7708
7709       // We only handle the case where V1 feeds the first slots of the unpack.
7710       // We rely on canonicalization to ensure this is the case.
7711       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7712         return SDValue();
7713
7714       // Setup the mask for this input. The indexing is tricky as we have to
7715       // handle the unpack stride.
7716       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7717       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7718           Mask[i] % Size;
7719     }
7720
7721     // If we will have to shuffle both inputs to use the unpack, check whether
7722     // we can just unpack first and shuffle the result. If so, skip this unpack.
7723     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7724         !isNoopShuffleMask(V2Mask))
7725       return SDValue();
7726
7727     // Shuffle the inputs into place.
7728     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7729     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7730
7731     // Cast the inputs to the type we will use to unpack them.
7732     V1 = DAG.getBitcast(UnpackVT, V1);
7733     V2 = DAG.getBitcast(UnpackVT, V2);
7734
7735     // Unpack the inputs and cast the result back to the desired type.
7736     return DAG.getBitcast(
7737         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7738                         UnpackVT, V1, V2));
7739   };
7740
7741   // We try each unpack from the largest to the smallest to try and find one
7742   // that fits this mask.
7743   int OrigNumElements = VT.getVectorNumElements();
7744   int OrigScalarSize = VT.getScalarSizeInBits();
7745   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7746     int Scale = ScalarSize / OrigScalarSize;
7747     int NumElements = OrigNumElements / Scale;
7748     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7749     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7750       return Unpack;
7751   }
7752
7753   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7754   // initial unpack.
7755   if (NumLoInputs == 0 || NumHiInputs == 0) {
7756     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7757            "We have to have *some* inputs!");
7758     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7759
7760     // FIXME: We could consider the total complexity of the permute of each
7761     // possible unpacking. Or at the least we should consider how many
7762     // half-crossings are created.
7763     // FIXME: We could consider commuting the unpacks.
7764
7765     SmallVector<int, 32> PermMask;
7766     PermMask.assign(Size, -1);
7767     for (int i = 0; i < Size; ++i) {
7768       if (Mask[i] < 0)
7769         continue;
7770
7771       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7772
7773       PermMask[i] =
7774           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7775     }
7776     return DAG.getVectorShuffle(
7777         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7778                             DL, VT, V1, V2),
7779         DAG.getUNDEF(VT), PermMask);
7780   }
7781
7782   return SDValue();
7783 }
7784
7785 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7786 ///
7787 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7788 /// support for floating point shuffles but not integer shuffles. These
7789 /// instructions will incur a domain crossing penalty on some chips though so
7790 /// it is better to avoid lowering through this for integer vectors where
7791 /// possible.
7792 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7793                                        const X86Subtarget *Subtarget,
7794                                        SelectionDAG &DAG) {
7795   SDLoc DL(Op);
7796   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7797   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7798   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7799   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7800   ArrayRef<int> Mask = SVOp->getMask();
7801   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7802
7803   if (isSingleInputShuffleMask(Mask)) {
7804     // Use low duplicate instructions for masks that match their pattern.
7805     if (Subtarget->hasSSE3())
7806       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7807         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7808
7809     // Straight shuffle of a single input vector. Simulate this by using the
7810     // single input as both of the "inputs" to this instruction..
7811     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7812
7813     if (Subtarget->hasAVX()) {
7814       // If we have AVX, we can use VPERMILPS which will allow folding a load
7815       // into the shuffle.
7816       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7817                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7818     }
7819
7820     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7821                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7822   }
7823   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7824   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7825
7826   // If we have a single input, insert that into V1 if we can do so cheaply.
7827   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7828     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7829             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7830       return Insertion;
7831     // Try inverting the insertion since for v2 masks it is easy to do and we
7832     // can't reliably sort the mask one way or the other.
7833     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7834                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7835     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7836             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7837       return Insertion;
7838   }
7839
7840   // Try to use one of the special instruction patterns to handle two common
7841   // blend patterns if a zero-blend above didn't work.
7842   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7843       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7844     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7845       // We can either use a special instruction to load over the low double or
7846       // to move just the low double.
7847       return DAG.getNode(
7848           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7849           DL, MVT::v2f64, V2,
7850           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7851
7852   if (Subtarget->hasSSE41())
7853     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7854                                                   Subtarget, DAG))
7855       return Blend;
7856
7857   // Use dedicated unpack instructions for masks that match their pattern.
7858   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7859     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7860   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7861     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7862
7863   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7864   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7865                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7866 }
7867
7868 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7869 ///
7870 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7871 /// the integer unit to minimize domain crossing penalties. However, for blends
7872 /// it falls back to the floating point shuffle operation with appropriate bit
7873 /// casting.
7874 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7875                                        const X86Subtarget *Subtarget,
7876                                        SelectionDAG &DAG) {
7877   SDLoc DL(Op);
7878   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7879   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7880   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7881   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7882   ArrayRef<int> Mask = SVOp->getMask();
7883   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7884
7885   if (isSingleInputShuffleMask(Mask)) {
7886     // Check for being able to broadcast a single element.
7887     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7888                                                           Mask, Subtarget, DAG))
7889       return Broadcast;
7890
7891     // Straight shuffle of a single input vector. For everything from SSE2
7892     // onward this has a single fast instruction with no scary immediates.
7893     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7894     V1 = DAG.getBitcast(MVT::v4i32, V1);
7895     int WidenedMask[4] = {
7896         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7897         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7898     return DAG.getBitcast(
7899         MVT::v2i64,
7900         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7901                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7902   }
7903   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7904   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7905   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7906   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7907
7908   // If we have a blend of two PACKUS operations an the blend aligns with the
7909   // low and half halves, we can just merge the PACKUS operations. This is
7910   // particularly important as it lets us merge shuffles that this routine itself
7911   // creates.
7912   auto GetPackNode = [](SDValue V) {
7913     while (V.getOpcode() == ISD::BITCAST)
7914       V = V.getOperand(0);
7915
7916     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7917   };
7918   if (SDValue V1Pack = GetPackNode(V1))
7919     if (SDValue V2Pack = GetPackNode(V2))
7920       return DAG.getBitcast(MVT::v2i64,
7921                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7922                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7923                                                      : V1Pack.getOperand(1),
7924                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7925                                                      : V2Pack.getOperand(1)));
7926
7927   // Try to use shift instructions.
7928   if (SDValue Shift =
7929           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7930     return Shift;
7931
7932   // When loading a scalar and then shuffling it into a vector we can often do
7933   // the insertion cheaply.
7934   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7935           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7936     return Insertion;
7937   // Try inverting the insertion since for v2 masks it is easy to do and we
7938   // can't reliably sort the mask one way or the other.
7939   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7940   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7941           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7942     return Insertion;
7943
7944   // We have different paths for blend lowering, but they all must use the
7945   // *exact* same predicate.
7946   bool IsBlendSupported = Subtarget->hasSSE41();
7947   if (IsBlendSupported)
7948     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7949                                                   Subtarget, DAG))
7950       return Blend;
7951
7952   // Use dedicated unpack instructions for masks that match their pattern.
7953   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7954     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7955   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7956     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7957
7958   // Try to use byte rotation instructions.
7959   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7960   if (Subtarget->hasSSSE3())
7961     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7962             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7963       return Rotate;
7964
7965   // If we have direct support for blends, we should lower by decomposing into
7966   // a permute. That will be faster than the domain cross.
7967   if (IsBlendSupported)
7968     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7969                                                       Mask, DAG);
7970
7971   // We implement this with SHUFPD which is pretty lame because it will likely
7972   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7973   // However, all the alternatives are still more cycles and newer chips don't
7974   // have this problem. It would be really nice if x86 had better shuffles here.
7975   V1 = DAG.getBitcast(MVT::v2f64, V1);
7976   V2 = DAG.getBitcast(MVT::v2f64, V2);
7977   return DAG.getBitcast(MVT::v2i64,
7978                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7979 }
7980
7981 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7982 ///
7983 /// This is used to disable more specialized lowerings when the shufps lowering
7984 /// will happen to be efficient.
7985 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7986   // This routine only handles 128-bit shufps.
7987   assert(Mask.size() == 4 && "Unsupported mask size!");
7988
7989   // To lower with a single SHUFPS we need to have the low half and high half
7990   // each requiring a single input.
7991   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7992     return false;
7993   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7994     return false;
7995
7996   return true;
7997 }
7998
7999 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8000 ///
8001 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8002 /// It makes no assumptions about whether this is the *best* lowering, it simply
8003 /// uses it.
8004 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8005                                             ArrayRef<int> Mask, SDValue V1,
8006                                             SDValue V2, SelectionDAG &DAG) {
8007   SDValue LowV = V1, HighV = V2;
8008   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8009
8010   int NumV2Elements =
8011       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8012
8013   if (NumV2Elements == 1) {
8014     int V2Index =
8015         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8016         Mask.begin();
8017
8018     // Compute the index adjacent to V2Index and in the same half by toggling
8019     // the low bit.
8020     int V2AdjIndex = V2Index ^ 1;
8021
8022     if (Mask[V2AdjIndex] == -1) {
8023       // Handles all the cases where we have a single V2 element and an undef.
8024       // This will only ever happen in the high lanes because we commute the
8025       // vector otherwise.
8026       if (V2Index < 2)
8027         std::swap(LowV, HighV);
8028       NewMask[V2Index] -= 4;
8029     } else {
8030       // Handle the case where the V2 element ends up adjacent to a V1 element.
8031       // To make this work, blend them together as the first step.
8032       int V1Index = V2AdjIndex;
8033       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8034       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8035                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8036
8037       // Now proceed to reconstruct the final blend as we have the necessary
8038       // high or low half formed.
8039       if (V2Index < 2) {
8040         LowV = V2;
8041         HighV = V1;
8042       } else {
8043         HighV = V2;
8044       }
8045       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8046       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8047     }
8048   } else if (NumV2Elements == 2) {
8049     if (Mask[0] < 4 && Mask[1] < 4) {
8050       // Handle the easy case where we have V1 in the low lanes and V2 in the
8051       // high lanes.
8052       NewMask[2] -= 4;
8053       NewMask[3] -= 4;
8054     } else if (Mask[2] < 4 && Mask[3] < 4) {
8055       // We also handle the reversed case because this utility may get called
8056       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8057       // arrange things in the right direction.
8058       NewMask[0] -= 4;
8059       NewMask[1] -= 4;
8060       HighV = V1;
8061       LowV = V2;
8062     } else {
8063       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8064       // trying to place elements directly, just blend them and set up the final
8065       // shuffle to place them.
8066
8067       // The first two blend mask elements are for V1, the second two are for
8068       // V2.
8069       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8070                           Mask[2] < 4 ? Mask[2] : Mask[3],
8071                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8072                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8073       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8074                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8075
8076       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8077       // a blend.
8078       LowV = HighV = V1;
8079       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8080       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8081       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8082       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8083     }
8084   }
8085   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8086                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8087 }
8088
8089 /// \brief Lower 4-lane 32-bit floating point shuffles.
8090 ///
8091 /// Uses instructions exclusively from the floating point unit to minimize
8092 /// domain crossing penalties, as these are sufficient to implement all v4f32
8093 /// shuffles.
8094 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8095                                        const X86Subtarget *Subtarget,
8096                                        SelectionDAG &DAG) {
8097   SDLoc DL(Op);
8098   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8099   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8100   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8102   ArrayRef<int> Mask = SVOp->getMask();
8103   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8104
8105   int NumV2Elements =
8106       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8107
8108   if (NumV2Elements == 0) {
8109     // Check for being able to broadcast a single element.
8110     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8111                                                           Mask, Subtarget, DAG))
8112       return Broadcast;
8113
8114     // Use even/odd duplicate instructions for masks that match their pattern.
8115     if (Subtarget->hasSSE3()) {
8116       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8117         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8118       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8119         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8120     }
8121
8122     if (Subtarget->hasAVX()) {
8123       // If we have AVX, we can use VPERMILPS which will allow folding a load
8124       // into the shuffle.
8125       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8126                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8127     }
8128
8129     // Otherwise, use a straight shuffle of a single input vector. We pass the
8130     // input vector to both operands to simulate this with a SHUFPS.
8131     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8132                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8133   }
8134
8135   // There are special ways we can lower some single-element blends. However, we
8136   // have custom ways we can lower more complex single-element blends below that
8137   // we defer to if both this and BLENDPS fail to match, so restrict this to
8138   // when the V2 input is targeting element 0 of the mask -- that is the fast
8139   // case here.
8140   if (NumV2Elements == 1 && Mask[0] >= 4)
8141     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8142                                                          Mask, Subtarget, DAG))
8143       return V;
8144
8145   if (Subtarget->hasSSE41()) {
8146     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8147                                                   Subtarget, DAG))
8148       return Blend;
8149
8150     // Use INSERTPS if we can complete the shuffle efficiently.
8151     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8152       return V;
8153
8154     if (!isSingleSHUFPSMask(Mask))
8155       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8156               DL, MVT::v4f32, V1, V2, Mask, DAG))
8157         return BlendPerm;
8158   }
8159
8160   // Use dedicated unpack instructions for masks that match their pattern.
8161   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8162     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8163   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8164     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8165   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8166     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8167   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8168     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8169
8170   // Otherwise fall back to a SHUFPS lowering strategy.
8171   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8172 }
8173
8174 /// \brief Lower 4-lane i32 vector shuffles.
8175 ///
8176 /// We try to handle these with integer-domain shuffles where we can, but for
8177 /// blends we use the floating point domain blend instructions.
8178 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8179                                        const X86Subtarget *Subtarget,
8180                                        SelectionDAG &DAG) {
8181   SDLoc DL(Op);
8182   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8183   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8184   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8185   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8186   ArrayRef<int> Mask = SVOp->getMask();
8187   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8188
8189   // Whenever we can lower this as a zext, that instruction is strictly faster
8190   // than any alternative. It also allows us to fold memory operands into the
8191   // shuffle in many cases.
8192   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8193                                                          Mask, Subtarget, DAG))
8194     return ZExt;
8195
8196   int NumV2Elements =
8197       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8198
8199   if (NumV2Elements == 0) {
8200     // Check for being able to broadcast a single element.
8201     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8202                                                           Mask, Subtarget, DAG))
8203       return Broadcast;
8204
8205     // Straight shuffle of a single input vector. For everything from SSE2
8206     // onward this has a single fast instruction with no scary immediates.
8207     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8208     // but we aren't actually going to use the UNPCK instruction because doing
8209     // so prevents folding a load into this instruction or making a copy.
8210     const int UnpackLoMask[] = {0, 0, 1, 1};
8211     const int UnpackHiMask[] = {2, 2, 3, 3};
8212     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8213       Mask = UnpackLoMask;
8214     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8215       Mask = UnpackHiMask;
8216
8217     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8218                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8219   }
8220
8221   // Try to use shift instructions.
8222   if (SDValue Shift =
8223           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8224     return Shift;
8225
8226   // There are special ways we can lower some single-element blends.
8227   if (NumV2Elements == 1)
8228     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8229                                                          Mask, Subtarget, DAG))
8230       return V;
8231
8232   // We have different paths for blend lowering, but they all must use the
8233   // *exact* same predicate.
8234   bool IsBlendSupported = Subtarget->hasSSE41();
8235   if (IsBlendSupported)
8236     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8237                                                   Subtarget, DAG))
8238       return Blend;
8239
8240   if (SDValue Masked =
8241           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8242     return Masked;
8243
8244   // Use dedicated unpack instructions for masks that match their pattern.
8245   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8246     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8247   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8248     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8249   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8250     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8251   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8252     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8253
8254   // Try to use byte rotation instructions.
8255   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8256   if (Subtarget->hasSSSE3())
8257     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8258             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8259       return Rotate;
8260
8261   // If we have direct support for blends, we should lower by decomposing into
8262   // a permute. That will be faster than the domain cross.
8263   if (IsBlendSupported)
8264     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8265                                                       Mask, DAG);
8266
8267   // Try to lower by permuting the inputs into an unpack instruction.
8268   if (SDValue Unpack =
8269           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8270     return Unpack;
8271
8272   // We implement this with SHUFPS because it can blend from two vectors.
8273   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8274   // up the inputs, bypassing domain shift penalties that we would encur if we
8275   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8276   // relevant.
8277   return DAG.getBitcast(
8278       MVT::v4i32,
8279       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8280                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8281 }
8282
8283 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8284 /// shuffle lowering, and the most complex part.
8285 ///
8286 /// The lowering strategy is to try to form pairs of input lanes which are
8287 /// targeted at the same half of the final vector, and then use a dword shuffle
8288 /// to place them onto the right half, and finally unpack the paired lanes into
8289 /// their final position.
8290 ///
8291 /// The exact breakdown of how to form these dword pairs and align them on the
8292 /// correct sides is really tricky. See the comments within the function for
8293 /// more of the details.
8294 ///
8295 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8296 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8297 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8298 /// vector, form the analogous 128-bit 8-element Mask.
8299 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8300     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8301     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8302   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8303   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8304
8305   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8306   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8307   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8308
8309   SmallVector<int, 4> LoInputs;
8310   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8311                [](int M) { return M >= 0; });
8312   std::sort(LoInputs.begin(), LoInputs.end());
8313   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8314   SmallVector<int, 4> HiInputs;
8315   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8316                [](int M) { return M >= 0; });
8317   std::sort(HiInputs.begin(), HiInputs.end());
8318   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8319   int NumLToL =
8320       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8321   int NumHToL = LoInputs.size() - NumLToL;
8322   int NumLToH =
8323       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8324   int NumHToH = HiInputs.size() - NumLToH;
8325   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8326   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8327   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8328   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8329
8330   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8331   // such inputs we can swap two of the dwords across the half mark and end up
8332   // with <=2 inputs to each half in each half. Once there, we can fall through
8333   // to the generic code below. For example:
8334   //
8335   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8336   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8337   //
8338   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8339   // and an existing 2-into-2 on the other half. In this case we may have to
8340   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8341   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8342   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8343   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8344   // half than the one we target for fixing) will be fixed when we re-enter this
8345   // path. We will also combine away any sequence of PSHUFD instructions that
8346   // result into a single instruction. Here is an example of the tricky case:
8347   //
8348   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8349   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8350   //
8351   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8352   //
8353   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8354   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8355   //
8356   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8357   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8358   //
8359   // The result is fine to be handled by the generic logic.
8360   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8361                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8362                           int AOffset, int BOffset) {
8363     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8364            "Must call this with A having 3 or 1 inputs from the A half.");
8365     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8366            "Must call this with B having 1 or 3 inputs from the B half.");
8367     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8368            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8369
8370     bool ThreeAInputs = AToAInputs.size() == 3;
8371
8372     // Compute the index of dword with only one word among the three inputs in
8373     // a half by taking the sum of the half with three inputs and subtracting
8374     // the sum of the actual three inputs. The difference is the remaining
8375     // slot.
8376     int ADWord, BDWord;
8377     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8378     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8379     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8380     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8381     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8382     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8383     int TripleNonInputIdx =
8384         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8385     TripleDWord = TripleNonInputIdx / 2;
8386
8387     // We use xor with one to compute the adjacent DWord to whichever one the
8388     // OneInput is in.
8389     OneInputDWord = (OneInput / 2) ^ 1;
8390
8391     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8392     // and BToA inputs. If there is also such a problem with the BToB and AToB
8393     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8394     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8395     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8396     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8397       // Compute how many inputs will be flipped by swapping these DWords. We
8398       // need
8399       // to balance this to ensure we don't form a 3-1 shuffle in the other
8400       // half.
8401       int NumFlippedAToBInputs =
8402           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8403           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8404       int NumFlippedBToBInputs =
8405           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8406           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8407       if ((NumFlippedAToBInputs == 1 &&
8408            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8409           (NumFlippedBToBInputs == 1 &&
8410            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8411         // We choose whether to fix the A half or B half based on whether that
8412         // half has zero flipped inputs. At zero, we may not be able to fix it
8413         // with that half. We also bias towards fixing the B half because that
8414         // will more commonly be the high half, and we have to bias one way.
8415         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8416                                                        ArrayRef<int> Inputs) {
8417           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8418           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8419                                          PinnedIdx ^ 1) != Inputs.end();
8420           // Determine whether the free index is in the flipped dword or the
8421           // unflipped dword based on where the pinned index is. We use this bit
8422           // in an xor to conditionally select the adjacent dword.
8423           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8424           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8425                                              FixFreeIdx) != Inputs.end();
8426           if (IsFixIdxInput == IsFixFreeIdxInput)
8427             FixFreeIdx += 1;
8428           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8429                                         FixFreeIdx) != Inputs.end();
8430           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8431                  "We need to be changing the number of flipped inputs!");
8432           int PSHUFHalfMask[] = {0, 1, 2, 3};
8433           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8434           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8435                           MVT::v8i16, V,
8436                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8437
8438           for (int &M : Mask)
8439             if (M != -1 && M == FixIdx)
8440               M = FixFreeIdx;
8441             else if (M != -1 && M == FixFreeIdx)
8442               M = FixIdx;
8443         };
8444         if (NumFlippedBToBInputs != 0) {
8445           int BPinnedIdx =
8446               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8447           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8448         } else {
8449           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8450           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8451           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8452         }
8453       }
8454     }
8455
8456     int PSHUFDMask[] = {0, 1, 2, 3};
8457     PSHUFDMask[ADWord] = BDWord;
8458     PSHUFDMask[BDWord] = ADWord;
8459     V = DAG.getBitcast(
8460         VT,
8461         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8462                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8463
8464     // Adjust the mask to match the new locations of A and B.
8465     for (int &M : Mask)
8466       if (M != -1 && M/2 == ADWord)
8467         M = 2 * BDWord + M % 2;
8468       else if (M != -1 && M/2 == BDWord)
8469         M = 2 * ADWord + M % 2;
8470
8471     // Recurse back into this routine to re-compute state now that this isn't
8472     // a 3 and 1 problem.
8473     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8474                                                      DAG);
8475   };
8476   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8477     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8478   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8479     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8480
8481   // At this point there are at most two inputs to the low and high halves from
8482   // each half. That means the inputs can always be grouped into dwords and
8483   // those dwords can then be moved to the correct half with a dword shuffle.
8484   // We use at most one low and one high word shuffle to collect these paired
8485   // inputs into dwords, and finally a dword shuffle to place them.
8486   int PSHUFLMask[4] = {-1, -1, -1, -1};
8487   int PSHUFHMask[4] = {-1, -1, -1, -1};
8488   int PSHUFDMask[4] = {-1, -1, -1, -1};
8489
8490   // First fix the masks for all the inputs that are staying in their
8491   // original halves. This will then dictate the targets of the cross-half
8492   // shuffles.
8493   auto fixInPlaceInputs =
8494       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8495                     MutableArrayRef<int> SourceHalfMask,
8496                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8497     if (InPlaceInputs.empty())
8498       return;
8499     if (InPlaceInputs.size() == 1) {
8500       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8501           InPlaceInputs[0] - HalfOffset;
8502       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8503       return;
8504     }
8505     if (IncomingInputs.empty()) {
8506       // Just fix all of the in place inputs.
8507       for (int Input : InPlaceInputs) {
8508         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8509         PSHUFDMask[Input / 2] = Input / 2;
8510       }
8511       return;
8512     }
8513
8514     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8515     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8516         InPlaceInputs[0] - HalfOffset;
8517     // Put the second input next to the first so that they are packed into
8518     // a dword. We find the adjacent index by toggling the low bit.
8519     int AdjIndex = InPlaceInputs[0] ^ 1;
8520     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8521     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8522     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8523   };
8524   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8525   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8526
8527   // Now gather the cross-half inputs and place them into a free dword of
8528   // their target half.
8529   // FIXME: This operation could almost certainly be simplified dramatically to
8530   // look more like the 3-1 fixing operation.
8531   auto moveInputsToRightHalf = [&PSHUFDMask](
8532       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8533       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8534       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8535       int DestOffset) {
8536     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8537       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8538     };
8539     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8540                                                int Word) {
8541       int LowWord = Word & ~1;
8542       int HighWord = Word | 1;
8543       return isWordClobbered(SourceHalfMask, LowWord) ||
8544              isWordClobbered(SourceHalfMask, HighWord);
8545     };
8546
8547     if (IncomingInputs.empty())
8548       return;
8549
8550     if (ExistingInputs.empty()) {
8551       // Map any dwords with inputs from them into the right half.
8552       for (int Input : IncomingInputs) {
8553         // If the source half mask maps over the inputs, turn those into
8554         // swaps and use the swapped lane.
8555         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8556           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8557             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8558                 Input - SourceOffset;
8559             // We have to swap the uses in our half mask in one sweep.
8560             for (int &M : HalfMask)
8561               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8562                 M = Input;
8563               else if (M == Input)
8564                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8565           } else {
8566             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8567                        Input - SourceOffset &&
8568                    "Previous placement doesn't match!");
8569           }
8570           // Note that this correctly re-maps both when we do a swap and when
8571           // we observe the other side of the swap above. We rely on that to
8572           // avoid swapping the members of the input list directly.
8573           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8574         }
8575
8576         // Map the input's dword into the correct half.
8577         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8578           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8579         else
8580           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8581                      Input / 2 &&
8582                  "Previous placement doesn't match!");
8583       }
8584
8585       // And just directly shift any other-half mask elements to be same-half
8586       // as we will have mirrored the dword containing the element into the
8587       // same position within that half.
8588       for (int &M : HalfMask)
8589         if (M >= SourceOffset && M < SourceOffset + 4) {
8590           M = M - SourceOffset + DestOffset;
8591           assert(M >= 0 && "This should never wrap below zero!");
8592         }
8593       return;
8594     }
8595
8596     // Ensure we have the input in a viable dword of its current half. This
8597     // is particularly tricky because the original position may be clobbered
8598     // by inputs being moved and *staying* in that half.
8599     if (IncomingInputs.size() == 1) {
8600       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8601         int InputFixed = std::find(std::begin(SourceHalfMask),
8602                                    std::end(SourceHalfMask), -1) -
8603                          std::begin(SourceHalfMask) + SourceOffset;
8604         SourceHalfMask[InputFixed - SourceOffset] =
8605             IncomingInputs[0] - SourceOffset;
8606         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8607                      InputFixed);
8608         IncomingInputs[0] = InputFixed;
8609       }
8610     } else if (IncomingInputs.size() == 2) {
8611       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8612           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8613         // We have two non-adjacent or clobbered inputs we need to extract from
8614         // the source half. To do this, we need to map them into some adjacent
8615         // dword slot in the source mask.
8616         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8617                               IncomingInputs[1] - SourceOffset};
8618
8619         // If there is a free slot in the source half mask adjacent to one of
8620         // the inputs, place the other input in it. We use (Index XOR 1) to
8621         // compute an adjacent index.
8622         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8623             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8624           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8625           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8626           InputsFixed[1] = InputsFixed[0] ^ 1;
8627         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8628                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8629           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8630           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8631           InputsFixed[0] = InputsFixed[1] ^ 1;
8632         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8633                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8634           // The two inputs are in the same DWord but it is clobbered and the
8635           // adjacent DWord isn't used at all. Move both inputs to the free
8636           // slot.
8637           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8638           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8639           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8640           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8641         } else {
8642           // The only way we hit this point is if there is no clobbering
8643           // (because there are no off-half inputs to this half) and there is no
8644           // free slot adjacent to one of the inputs. In this case, we have to
8645           // swap an input with a non-input.
8646           for (int i = 0; i < 4; ++i)
8647             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8648                    "We can't handle any clobbers here!");
8649           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8650                  "Cannot have adjacent inputs here!");
8651
8652           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8653           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8654
8655           // We also have to update the final source mask in this case because
8656           // it may need to undo the above swap.
8657           for (int &M : FinalSourceHalfMask)
8658             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8659               M = InputsFixed[1] + SourceOffset;
8660             else if (M == InputsFixed[1] + SourceOffset)
8661               M = (InputsFixed[0] ^ 1) + SourceOffset;
8662
8663           InputsFixed[1] = InputsFixed[0] ^ 1;
8664         }
8665
8666         // Point everything at the fixed inputs.
8667         for (int &M : HalfMask)
8668           if (M == IncomingInputs[0])
8669             M = InputsFixed[0] + SourceOffset;
8670           else if (M == IncomingInputs[1])
8671             M = InputsFixed[1] + SourceOffset;
8672
8673         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8674         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8675       }
8676     } else {
8677       llvm_unreachable("Unhandled input size!");
8678     }
8679
8680     // Now hoist the DWord down to the right half.
8681     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8682     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8683     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8684     for (int &M : HalfMask)
8685       for (int Input : IncomingInputs)
8686         if (M == Input)
8687           M = FreeDWord * 2 + Input % 2;
8688   };
8689   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8690                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8691   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8692                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8693
8694   // Now enact all the shuffles we've computed to move the inputs into their
8695   // target half.
8696   if (!isNoopShuffleMask(PSHUFLMask))
8697     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8698                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8699   if (!isNoopShuffleMask(PSHUFHMask))
8700     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8701                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8702   if (!isNoopShuffleMask(PSHUFDMask))
8703     V = DAG.getBitcast(
8704         VT,
8705         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8706                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8707
8708   // At this point, each half should contain all its inputs, and we can then
8709   // just shuffle them into their final position.
8710   assert(std::count_if(LoMask.begin(), LoMask.end(),
8711                        [](int M) { return M >= 4; }) == 0 &&
8712          "Failed to lift all the high half inputs to the low mask!");
8713   assert(std::count_if(HiMask.begin(), HiMask.end(),
8714                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8715          "Failed to lift all the low half inputs to the high mask!");
8716
8717   // Do a half shuffle for the low mask.
8718   if (!isNoopShuffleMask(LoMask))
8719     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8720                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8721
8722   // Do a half shuffle with the high mask after shifting its values down.
8723   for (int &M : HiMask)
8724     if (M >= 0)
8725       M -= 4;
8726   if (!isNoopShuffleMask(HiMask))
8727     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8728                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8729
8730   return V;
8731 }
8732
8733 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8734 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8735                                           SDValue V2, ArrayRef<int> Mask,
8736                                           SelectionDAG &DAG, bool &V1InUse,
8737                                           bool &V2InUse) {
8738   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8739   SDValue V1Mask[16];
8740   SDValue V2Mask[16];
8741   V1InUse = false;
8742   V2InUse = false;
8743
8744   int Size = Mask.size();
8745   int Scale = 16 / Size;
8746   for (int i = 0; i < 16; ++i) {
8747     if (Mask[i / Scale] == -1) {
8748       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8749     } else {
8750       const int ZeroMask = 0x80;
8751       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8752                                           : ZeroMask;
8753       int V2Idx = Mask[i / Scale] < Size
8754                       ? ZeroMask
8755                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8756       if (Zeroable[i / Scale])
8757         V1Idx = V2Idx = ZeroMask;
8758       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8759       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8760       V1InUse |= (ZeroMask != V1Idx);
8761       V2InUse |= (ZeroMask != V2Idx);
8762     }
8763   }
8764
8765   if (V1InUse)
8766     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8767                      DAG.getBitcast(MVT::v16i8, V1),
8768                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8769   if (V2InUse)
8770     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8771                      DAG.getBitcast(MVT::v16i8, V2),
8772                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8773
8774   // If we need shuffled inputs from both, blend the two.
8775   SDValue V;
8776   if (V1InUse && V2InUse)
8777     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8778   else
8779     V = V1InUse ? V1 : V2;
8780
8781   // Cast the result back to the correct type.
8782   return DAG.getBitcast(VT, V);
8783 }
8784
8785 /// \brief Generic lowering of 8-lane i16 shuffles.
8786 ///
8787 /// This handles both single-input shuffles and combined shuffle/blends with
8788 /// two inputs. The single input shuffles are immediately delegated to
8789 /// a dedicated lowering routine.
8790 ///
8791 /// The blends are lowered in one of three fundamental ways. If there are few
8792 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8793 /// of the input is significantly cheaper when lowered as an interleaving of
8794 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8795 /// halves of the inputs separately (making them have relatively few inputs)
8796 /// and then concatenate them.
8797 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8798                                        const X86Subtarget *Subtarget,
8799                                        SelectionDAG &DAG) {
8800   SDLoc DL(Op);
8801   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8802   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8803   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8804   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8805   ArrayRef<int> OrigMask = SVOp->getMask();
8806   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8807                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8808   MutableArrayRef<int> Mask(MaskStorage);
8809
8810   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8811
8812   // Whenever we can lower this as a zext, that instruction is strictly faster
8813   // than any alternative.
8814   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8815           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8816     return ZExt;
8817
8818   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8819   (void)isV1;
8820   auto isV2 = [](int M) { return M >= 8; };
8821
8822   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8823
8824   if (NumV2Inputs == 0) {
8825     // Check for being able to broadcast a single element.
8826     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8827                                                           Mask, Subtarget, DAG))
8828       return Broadcast;
8829
8830     // Try to use shift instructions.
8831     if (SDValue Shift =
8832             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8833       return Shift;
8834
8835     // Use dedicated unpack instructions for masks that match their pattern.
8836     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8837       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8838     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8839       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8840
8841     // Try to use byte rotation instructions.
8842     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8843                                                         Mask, Subtarget, DAG))
8844       return Rotate;
8845
8846     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8847                                                      Subtarget, DAG);
8848   }
8849
8850   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8851          "All single-input shuffles should be canonicalized to be V1-input "
8852          "shuffles.");
8853
8854   // Try to use shift instructions.
8855   if (SDValue Shift =
8856           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8857     return Shift;
8858
8859   // See if we can use SSE4A Extraction / Insertion.
8860   if (Subtarget->hasSSE4A())
8861     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8862       return V;
8863
8864   // There are special ways we can lower some single-element blends.
8865   if (NumV2Inputs == 1)
8866     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8867                                                          Mask, Subtarget, DAG))
8868       return V;
8869
8870   // We have different paths for blend lowering, but they all must use the
8871   // *exact* same predicate.
8872   bool IsBlendSupported = Subtarget->hasSSE41();
8873   if (IsBlendSupported)
8874     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8875                                                   Subtarget, DAG))
8876       return Blend;
8877
8878   if (SDValue Masked =
8879           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8880     return Masked;
8881
8882   // Use dedicated unpack instructions for masks that match their pattern.
8883   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8884     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8885   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8886     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8887
8888   // Try to use byte rotation instructions.
8889   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8890           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8891     return Rotate;
8892
8893   if (SDValue BitBlend =
8894           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8895     return BitBlend;
8896
8897   if (SDValue Unpack =
8898           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8899     return Unpack;
8900
8901   // If we can't directly blend but can use PSHUFB, that will be better as it
8902   // can both shuffle and set up the inefficient blend.
8903   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8904     bool V1InUse, V2InUse;
8905     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8906                                       V1InUse, V2InUse);
8907   }
8908
8909   // We can always bit-blend if we have to so the fallback strategy is to
8910   // decompose into single-input permutes and blends.
8911   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8912                                                       Mask, DAG);
8913 }
8914
8915 /// \brief Check whether a compaction lowering can be done by dropping even
8916 /// elements and compute how many times even elements must be dropped.
8917 ///
8918 /// This handles shuffles which take every Nth element where N is a power of
8919 /// two. Example shuffle masks:
8920 ///
8921 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8922 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8923 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8924 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8925 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8926 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8927 ///
8928 /// Any of these lanes can of course be undef.
8929 ///
8930 /// This routine only supports N <= 3.
8931 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8932 /// for larger N.
8933 ///
8934 /// \returns N above, or the number of times even elements must be dropped if
8935 /// there is such a number. Otherwise returns zero.
8936 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8937   // Figure out whether we're looping over two inputs or just one.
8938   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8939
8940   // The modulus for the shuffle vector entries is based on whether this is
8941   // a single input or not.
8942   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8943   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8944          "We should only be called with masks with a power-of-2 size!");
8945
8946   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8947
8948   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8949   // and 2^3 simultaneously. This is because we may have ambiguity with
8950   // partially undef inputs.
8951   bool ViableForN[3] = {true, true, true};
8952
8953   for (int i = 0, e = Mask.size(); i < e; ++i) {
8954     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8955     // want.
8956     if (Mask[i] == -1)
8957       continue;
8958
8959     bool IsAnyViable = false;
8960     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8961       if (ViableForN[j]) {
8962         uint64_t N = j + 1;
8963
8964         // The shuffle mask must be equal to (i * 2^N) % M.
8965         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8966           IsAnyViable = true;
8967         else
8968           ViableForN[j] = false;
8969       }
8970     // Early exit if we exhaust the possible powers of two.
8971     if (!IsAnyViable)
8972       break;
8973   }
8974
8975   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8976     if (ViableForN[j])
8977       return j + 1;
8978
8979   // Return 0 as there is no viable power of two.
8980   return 0;
8981 }
8982
8983 /// \brief Generic lowering of v16i8 shuffles.
8984 ///
8985 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8986 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8987 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8988 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8989 /// back together.
8990 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8991                                        const X86Subtarget *Subtarget,
8992                                        SelectionDAG &DAG) {
8993   SDLoc DL(Op);
8994   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8995   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8996   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8997   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8998   ArrayRef<int> Mask = SVOp->getMask();
8999   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9000
9001   // Try to use shift instructions.
9002   if (SDValue Shift =
9003           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9004     return Shift;
9005
9006   // Try to use byte rotation instructions.
9007   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9008           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9009     return Rotate;
9010
9011   // Try to use a zext lowering.
9012   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9013           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9014     return ZExt;
9015
9016   // See if we can use SSE4A Extraction / Insertion.
9017   if (Subtarget->hasSSE4A())
9018     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9019       return V;
9020
9021   int NumV2Elements =
9022       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9023
9024   // For single-input shuffles, there are some nicer lowering tricks we can use.
9025   if (NumV2Elements == 0) {
9026     // Check for being able to broadcast a single element.
9027     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9028                                                           Mask, Subtarget, DAG))
9029       return Broadcast;
9030
9031     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9032     // Notably, this handles splat and partial-splat shuffles more efficiently.
9033     // However, it only makes sense if the pre-duplication shuffle simplifies
9034     // things significantly. Currently, this means we need to be able to
9035     // express the pre-duplication shuffle as an i16 shuffle.
9036     //
9037     // FIXME: We should check for other patterns which can be widened into an
9038     // i16 shuffle as well.
9039     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9040       for (int i = 0; i < 16; i += 2)
9041         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9042           return false;
9043
9044       return true;
9045     };
9046     auto tryToWidenViaDuplication = [&]() -> SDValue {
9047       if (!canWidenViaDuplication(Mask))
9048         return SDValue();
9049       SmallVector<int, 4> LoInputs;
9050       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9051                    [](int M) { return M >= 0 && M < 8; });
9052       std::sort(LoInputs.begin(), LoInputs.end());
9053       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9054                      LoInputs.end());
9055       SmallVector<int, 4> HiInputs;
9056       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9057                    [](int M) { return M >= 8; });
9058       std::sort(HiInputs.begin(), HiInputs.end());
9059       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9060                      HiInputs.end());
9061
9062       bool TargetLo = LoInputs.size() >= HiInputs.size();
9063       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9064       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9065
9066       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9067       SmallDenseMap<int, int, 8> LaneMap;
9068       for (int I : InPlaceInputs) {
9069         PreDupI16Shuffle[I/2] = I/2;
9070         LaneMap[I] = I;
9071       }
9072       int j = TargetLo ? 0 : 4, je = j + 4;
9073       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9074         // Check if j is already a shuffle of this input. This happens when
9075         // there are two adjacent bytes after we move the low one.
9076         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9077           // If we haven't yet mapped the input, search for a slot into which
9078           // we can map it.
9079           while (j < je && PreDupI16Shuffle[j] != -1)
9080             ++j;
9081
9082           if (j == je)
9083             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9084             return SDValue();
9085
9086           // Map this input with the i16 shuffle.
9087           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9088         }
9089
9090         // Update the lane map based on the mapping we ended up with.
9091         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9092       }
9093       V1 = DAG.getBitcast(
9094           MVT::v16i8,
9095           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9096                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9097
9098       // Unpack the bytes to form the i16s that will be shuffled into place.
9099       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9100                        MVT::v16i8, V1, V1);
9101
9102       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9103       for (int i = 0; i < 16; ++i)
9104         if (Mask[i] != -1) {
9105           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9106           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9107           if (PostDupI16Shuffle[i / 2] == -1)
9108             PostDupI16Shuffle[i / 2] = MappedMask;
9109           else
9110             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9111                    "Conflicting entrties in the original shuffle!");
9112         }
9113       return DAG.getBitcast(
9114           MVT::v16i8,
9115           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9116                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9117     };
9118     if (SDValue V = tryToWidenViaDuplication())
9119       return V;
9120   }
9121
9122   if (SDValue Masked =
9123           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9124     return Masked;
9125
9126   // Use dedicated unpack instructions for masks that match their pattern.
9127   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9128                                          0, 16, 1, 17, 2, 18, 3, 19,
9129                                          // High half.
9130                                          4, 20, 5, 21, 6, 22, 7, 23}))
9131     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9132   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9133                                          8, 24, 9, 25, 10, 26, 11, 27,
9134                                          // High half.
9135                                          12, 28, 13, 29, 14, 30, 15, 31}))
9136     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9137
9138   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9139   // with PSHUFB. It is important to do this before we attempt to generate any
9140   // blends but after all of the single-input lowerings. If the single input
9141   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9142   // want to preserve that and we can DAG combine any longer sequences into
9143   // a PSHUFB in the end. But once we start blending from multiple inputs,
9144   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9145   // and there are *very* few patterns that would actually be faster than the
9146   // PSHUFB approach because of its ability to zero lanes.
9147   //
9148   // FIXME: The only exceptions to the above are blends which are exact
9149   // interleavings with direct instructions supporting them. We currently don't
9150   // handle those well here.
9151   if (Subtarget->hasSSSE3()) {
9152     bool V1InUse = false;
9153     bool V2InUse = false;
9154
9155     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9156                                                 DAG, V1InUse, V2InUse);
9157
9158     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9159     // do so. This avoids using them to handle blends-with-zero which is
9160     // important as a single pshufb is significantly faster for that.
9161     if (V1InUse && V2InUse) {
9162       if (Subtarget->hasSSE41())
9163         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9164                                                       Mask, Subtarget, DAG))
9165           return Blend;
9166
9167       // We can use an unpack to do the blending rather than an or in some
9168       // cases. Even though the or may be (very minorly) more efficient, we
9169       // preference this lowering because there are common cases where part of
9170       // the complexity of the shuffles goes away when we do the final blend as
9171       // an unpack.
9172       // FIXME: It might be worth trying to detect if the unpack-feeding
9173       // shuffles will both be pshufb, in which case we shouldn't bother with
9174       // this.
9175       if (SDValue Unpack =
9176               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9177         return Unpack;
9178     }
9179
9180     return PSHUFB;
9181   }
9182
9183   // There are special ways we can lower some single-element blends.
9184   if (NumV2Elements == 1)
9185     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9186                                                          Mask, Subtarget, DAG))
9187       return V;
9188
9189   if (SDValue BitBlend =
9190           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9191     return BitBlend;
9192
9193   // Check whether a compaction lowering can be done. This handles shuffles
9194   // which take every Nth element for some even N. See the helper function for
9195   // details.
9196   //
9197   // We special case these as they can be particularly efficiently handled with
9198   // the PACKUSB instruction on x86 and they show up in common patterns of
9199   // rearranging bytes to truncate wide elements.
9200   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9201     // NumEvenDrops is the power of two stride of the elements. Another way of
9202     // thinking about it is that we need to drop the even elements this many
9203     // times to get the original input.
9204     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9205
9206     // First we need to zero all the dropped bytes.
9207     assert(NumEvenDrops <= 3 &&
9208            "No support for dropping even elements more than 3 times.");
9209     // We use the mask type to pick which bytes are preserved based on how many
9210     // elements are dropped.
9211     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9212     SDValue ByteClearMask = DAG.getBitcast(
9213         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9214     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9215     if (!IsSingleInput)
9216       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9217
9218     // Now pack things back together.
9219     V1 = DAG.getBitcast(MVT::v8i16, V1);
9220     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9221     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9222     for (int i = 1; i < NumEvenDrops; ++i) {
9223       Result = DAG.getBitcast(MVT::v8i16, Result);
9224       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9225     }
9226
9227     return Result;
9228   }
9229
9230   // Handle multi-input cases by blending single-input shuffles.
9231   if (NumV2Elements > 0)
9232     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9233                                                       Mask, DAG);
9234
9235   // The fallback path for single-input shuffles widens this into two v8i16
9236   // vectors with unpacks, shuffles those, and then pulls them back together
9237   // with a pack.
9238   SDValue V = V1;
9239
9240   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9241   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9242   for (int i = 0; i < 16; ++i)
9243     if (Mask[i] >= 0)
9244       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9245
9246   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9247
9248   SDValue VLoHalf, VHiHalf;
9249   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9250   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9251   // i16s.
9252   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9253                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9254       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9255                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9256     // Use a mask to drop the high bytes.
9257     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9258     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9259                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9260
9261     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9262     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9263
9264     // Squash the masks to point directly into VLoHalf.
9265     for (int &M : LoBlendMask)
9266       if (M >= 0)
9267         M /= 2;
9268     for (int &M : HiBlendMask)
9269       if (M >= 0)
9270         M /= 2;
9271   } else {
9272     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9273     // VHiHalf so that we can blend them as i16s.
9274     VLoHalf = DAG.getBitcast(
9275         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9276     VHiHalf = DAG.getBitcast(
9277         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9278   }
9279
9280   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9281   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9282
9283   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9284 }
9285
9286 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9287 ///
9288 /// This routine breaks down the specific type of 128-bit shuffle and
9289 /// dispatches to the lowering routines accordingly.
9290 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9291                                         MVT VT, const X86Subtarget *Subtarget,
9292                                         SelectionDAG &DAG) {
9293   switch (VT.SimpleTy) {
9294   case MVT::v2i64:
9295     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9296   case MVT::v2f64:
9297     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9298   case MVT::v4i32:
9299     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9300   case MVT::v4f32:
9301     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9302   case MVT::v8i16:
9303     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9304   case MVT::v16i8:
9305     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9306
9307   default:
9308     llvm_unreachable("Unimplemented!");
9309   }
9310 }
9311
9312 /// \brief Helper function to test whether a shuffle mask could be
9313 /// simplified by widening the elements being shuffled.
9314 ///
9315 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9316 /// leaves it in an unspecified state.
9317 ///
9318 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9319 /// shuffle masks. The latter have the special property of a '-2' representing
9320 /// a zero-ed lane of a vector.
9321 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9322                                     SmallVectorImpl<int> &WidenedMask) {
9323   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9324     // If both elements are undef, its trivial.
9325     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9326       WidenedMask.push_back(SM_SentinelUndef);
9327       continue;
9328     }
9329
9330     // Check for an undef mask and a mask value properly aligned to fit with
9331     // a pair of values. If we find such a case, use the non-undef mask's value.
9332     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9333       WidenedMask.push_back(Mask[i + 1] / 2);
9334       continue;
9335     }
9336     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9337       WidenedMask.push_back(Mask[i] / 2);
9338       continue;
9339     }
9340
9341     // When zeroing, we need to spread the zeroing across both lanes to widen.
9342     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9343       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9344           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9345         WidenedMask.push_back(SM_SentinelZero);
9346         continue;
9347       }
9348       return false;
9349     }
9350
9351     // Finally check if the two mask values are adjacent and aligned with
9352     // a pair.
9353     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9354       WidenedMask.push_back(Mask[i] / 2);
9355       continue;
9356     }
9357
9358     // Otherwise we can't safely widen the elements used in this shuffle.
9359     return false;
9360   }
9361   assert(WidenedMask.size() == Mask.size() / 2 &&
9362          "Incorrect size of mask after widening the elements!");
9363
9364   return true;
9365 }
9366
9367 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9368 ///
9369 /// This routine just extracts two subvectors, shuffles them independently, and
9370 /// then concatenates them back together. This should work effectively with all
9371 /// AVX vector shuffle types.
9372 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9373                                           SDValue V2, ArrayRef<int> Mask,
9374                                           SelectionDAG &DAG) {
9375   assert(VT.getSizeInBits() >= 256 &&
9376          "Only for 256-bit or wider vector shuffles!");
9377   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9378   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9379
9380   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9381   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9382
9383   int NumElements = VT.getVectorNumElements();
9384   int SplitNumElements = NumElements / 2;
9385   MVT ScalarVT = VT.getScalarType();
9386   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9387
9388   // Rather than splitting build-vectors, just build two narrower build
9389   // vectors. This helps shuffling with splats and zeros.
9390   auto SplitVector = [&](SDValue V) {
9391     while (V.getOpcode() == ISD::BITCAST)
9392       V = V->getOperand(0);
9393
9394     MVT OrigVT = V.getSimpleValueType();
9395     int OrigNumElements = OrigVT.getVectorNumElements();
9396     int OrigSplitNumElements = OrigNumElements / 2;
9397     MVT OrigScalarVT = OrigVT.getScalarType();
9398     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9399
9400     SDValue LoV, HiV;
9401
9402     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9403     if (!BV) {
9404       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9405                         DAG.getIntPtrConstant(0, DL));
9406       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9407                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9408     } else {
9409
9410       SmallVector<SDValue, 16> LoOps, HiOps;
9411       for (int i = 0; i < OrigSplitNumElements; ++i) {
9412         LoOps.push_back(BV->getOperand(i));
9413         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9414       }
9415       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9416       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9417     }
9418     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9419                           DAG.getBitcast(SplitVT, HiV));
9420   };
9421
9422   SDValue LoV1, HiV1, LoV2, HiV2;
9423   std::tie(LoV1, HiV1) = SplitVector(V1);
9424   std::tie(LoV2, HiV2) = SplitVector(V2);
9425
9426   // Now create two 4-way blends of these half-width vectors.
9427   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9428     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9429     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9430     for (int i = 0; i < SplitNumElements; ++i) {
9431       int M = HalfMask[i];
9432       if (M >= NumElements) {
9433         if (M >= NumElements + SplitNumElements)
9434           UseHiV2 = true;
9435         else
9436           UseLoV2 = true;
9437         V2BlendMask.push_back(M - NumElements);
9438         V1BlendMask.push_back(-1);
9439         BlendMask.push_back(SplitNumElements + i);
9440       } else if (M >= 0) {
9441         if (M >= SplitNumElements)
9442           UseHiV1 = true;
9443         else
9444           UseLoV1 = true;
9445         V2BlendMask.push_back(-1);
9446         V1BlendMask.push_back(M);
9447         BlendMask.push_back(i);
9448       } else {
9449         V2BlendMask.push_back(-1);
9450         V1BlendMask.push_back(-1);
9451         BlendMask.push_back(-1);
9452       }
9453     }
9454
9455     // Because the lowering happens after all combining takes place, we need to
9456     // manually combine these blend masks as much as possible so that we create
9457     // a minimal number of high-level vector shuffle nodes.
9458
9459     // First try just blending the halves of V1 or V2.
9460     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9461       return DAG.getUNDEF(SplitVT);
9462     if (!UseLoV2 && !UseHiV2)
9463       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9464     if (!UseLoV1 && !UseHiV1)
9465       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9466
9467     SDValue V1Blend, V2Blend;
9468     if (UseLoV1 && UseHiV1) {
9469       V1Blend =
9470         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9471     } else {
9472       // We only use half of V1 so map the usage down into the final blend mask.
9473       V1Blend = UseLoV1 ? LoV1 : HiV1;
9474       for (int i = 0; i < SplitNumElements; ++i)
9475         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9476           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9477     }
9478     if (UseLoV2 && UseHiV2) {
9479       V2Blend =
9480         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9481     } else {
9482       // We only use half of V2 so map the usage down into the final blend mask.
9483       V2Blend = UseLoV2 ? LoV2 : HiV2;
9484       for (int i = 0; i < SplitNumElements; ++i)
9485         if (BlendMask[i] >= SplitNumElements)
9486           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9487     }
9488     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9489   };
9490   SDValue Lo = HalfBlend(LoMask);
9491   SDValue Hi = HalfBlend(HiMask);
9492   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9493 }
9494
9495 /// \brief Either split a vector in halves or decompose the shuffles and the
9496 /// blend.
9497 ///
9498 /// This is provided as a good fallback for many lowerings of non-single-input
9499 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9500 /// between splitting the shuffle into 128-bit components and stitching those
9501 /// back together vs. extracting the single-input shuffles and blending those
9502 /// results.
9503 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9504                                                 SDValue V2, ArrayRef<int> Mask,
9505                                                 SelectionDAG &DAG) {
9506   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9507                                             "lower single-input shuffles as it "
9508                                             "could then recurse on itself.");
9509   int Size = Mask.size();
9510
9511   // If this can be modeled as a broadcast of two elements followed by a blend,
9512   // prefer that lowering. This is especially important because broadcasts can
9513   // often fold with memory operands.
9514   auto DoBothBroadcast = [&] {
9515     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9516     for (int M : Mask)
9517       if (M >= Size) {
9518         if (V2BroadcastIdx == -1)
9519           V2BroadcastIdx = M - Size;
9520         else if (M - Size != V2BroadcastIdx)
9521           return false;
9522       } else if (M >= 0) {
9523         if (V1BroadcastIdx == -1)
9524           V1BroadcastIdx = M;
9525         else if (M != V1BroadcastIdx)
9526           return false;
9527       }
9528     return true;
9529   };
9530   if (DoBothBroadcast())
9531     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9532                                                       DAG);
9533
9534   // If the inputs all stem from a single 128-bit lane of each input, then we
9535   // split them rather than blending because the split will decompose to
9536   // unusually few instructions.
9537   int LaneCount = VT.getSizeInBits() / 128;
9538   int LaneSize = Size / LaneCount;
9539   SmallBitVector LaneInputs[2];
9540   LaneInputs[0].resize(LaneCount, false);
9541   LaneInputs[1].resize(LaneCount, false);
9542   for (int i = 0; i < Size; ++i)
9543     if (Mask[i] >= 0)
9544       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9545   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9546     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9547
9548   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9549   // that the decomposed single-input shuffles don't end up here.
9550   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9551 }
9552
9553 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9554 /// a permutation and blend of those lanes.
9555 ///
9556 /// This essentially blends the out-of-lane inputs to each lane into the lane
9557 /// from a permuted copy of the vector. This lowering strategy results in four
9558 /// instructions in the worst case for a single-input cross lane shuffle which
9559 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9560 /// of. Special cases for each particular shuffle pattern should be handled
9561 /// prior to trying this lowering.
9562 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9563                                                        SDValue V1, SDValue V2,
9564                                                        ArrayRef<int> Mask,
9565                                                        SelectionDAG &DAG) {
9566   // FIXME: This should probably be generalized for 512-bit vectors as well.
9567   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9568   int LaneSize = Mask.size() / 2;
9569
9570   // If there are only inputs from one 128-bit lane, splitting will in fact be
9571   // less expensive. The flags track whether the given lane contains an element
9572   // that crosses to another lane.
9573   bool LaneCrossing[2] = {false, false};
9574   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9575     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9576       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9577   if (!LaneCrossing[0] || !LaneCrossing[1])
9578     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9579
9580   if (isSingleInputShuffleMask(Mask)) {
9581     SmallVector<int, 32> FlippedBlendMask;
9582     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9583       FlippedBlendMask.push_back(
9584           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9585                                   ? Mask[i]
9586                                   : Mask[i] % LaneSize +
9587                                         (i / LaneSize) * LaneSize + Size));
9588
9589     // Flip the vector, and blend the results which should now be in-lane. The
9590     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9591     // 5 for the high source. The value 3 selects the high half of source 2 and
9592     // the value 2 selects the low half of source 2. We only use source 2 to
9593     // allow folding it into a memory operand.
9594     unsigned PERMMask = 3 | 2 << 4;
9595     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9596                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9597     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9598   }
9599
9600   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9601   // will be handled by the above logic and a blend of the results, much like
9602   // other patterns in AVX.
9603   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9604 }
9605
9606 /// \brief Handle lowering 2-lane 128-bit shuffles.
9607 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9608                                         SDValue V2, ArrayRef<int> Mask,
9609                                         const X86Subtarget *Subtarget,
9610                                         SelectionDAG &DAG) {
9611   // TODO: If minimizing size and one of the inputs is a zero vector and the
9612   // the zero vector has only one use, we could use a VPERM2X128 to save the
9613   // instruction bytes needed to explicitly generate the zero vector.
9614
9615   // Blends are faster and handle all the non-lane-crossing cases.
9616   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9617                                                 Subtarget, DAG))
9618     return Blend;
9619
9620   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9621   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9622
9623   // If either input operand is a zero vector, use VPERM2X128 because its mask
9624   // allows us to replace the zero input with an implicit zero.
9625   if (!IsV1Zero && !IsV2Zero) {
9626     // Check for patterns which can be matched with a single insert of a 128-bit
9627     // subvector.
9628     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9629     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9630       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9631                                    VT.getVectorNumElements() / 2);
9632       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9633                                 DAG.getIntPtrConstant(0, DL));
9634       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9635                                 OnlyUsesV1 ? V1 : V2,
9636                                 DAG.getIntPtrConstant(0, DL));
9637       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9638     }
9639   }
9640
9641   // Otherwise form a 128-bit permutation. After accounting for undefs,
9642   // convert the 64-bit shuffle mask selection values into 128-bit
9643   // selection bits by dividing the indexes by 2 and shifting into positions
9644   // defined by a vperm2*128 instruction's immediate control byte.
9645
9646   // The immediate permute control byte looks like this:
9647   //    [1:0] - select 128 bits from sources for low half of destination
9648   //    [2]   - ignore
9649   //    [3]   - zero low half of destination
9650   //    [5:4] - select 128 bits from sources for high half of destination
9651   //    [6]   - ignore
9652   //    [7]   - zero high half of destination
9653
9654   int MaskLO = Mask[0];
9655   if (MaskLO == SM_SentinelUndef)
9656     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9657
9658   int MaskHI = Mask[2];
9659   if (MaskHI == SM_SentinelUndef)
9660     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9661
9662   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9663
9664   // If either input is a zero vector, replace it with an undef input.
9665   // Shuffle mask values <  4 are selecting elements of V1.
9666   // Shuffle mask values >= 4 are selecting elements of V2.
9667   // Adjust each half of the permute mask by clearing the half that was
9668   // selecting the zero vector and setting the zero mask bit.
9669   if (IsV1Zero) {
9670     V1 = DAG.getUNDEF(VT);
9671     if (MaskLO < 4)
9672       PermMask = (PermMask & 0xf0) | 0x08;
9673     if (MaskHI < 4)
9674       PermMask = (PermMask & 0x0f) | 0x80;
9675   }
9676   if (IsV2Zero) {
9677     V2 = DAG.getUNDEF(VT);
9678     if (MaskLO >= 4)
9679       PermMask = (PermMask & 0xf0) | 0x08;
9680     if (MaskHI >= 4)
9681       PermMask = (PermMask & 0x0f) | 0x80;
9682   }
9683
9684   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9685                      DAG.getConstant(PermMask, DL, MVT::i8));
9686 }
9687
9688 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9689 /// shuffling each lane.
9690 ///
9691 /// This will only succeed when the result of fixing the 128-bit lanes results
9692 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9693 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9694 /// the lane crosses early and then use simpler shuffles within each lane.
9695 ///
9696 /// FIXME: It might be worthwhile at some point to support this without
9697 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9698 /// in x86 only floating point has interesting non-repeating shuffles, and even
9699 /// those are still *marginally* more expensive.
9700 static SDValue lowerVectorShuffleByMerging128BitLanes(
9701     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9702     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9703   assert(!isSingleInputShuffleMask(Mask) &&
9704          "This is only useful with multiple inputs.");
9705
9706   int Size = Mask.size();
9707   int LaneSize = 128 / VT.getScalarSizeInBits();
9708   int NumLanes = Size / LaneSize;
9709   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9710
9711   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9712   // check whether the in-128-bit lane shuffles share a repeating pattern.
9713   SmallVector<int, 4> Lanes;
9714   Lanes.resize(NumLanes, -1);
9715   SmallVector<int, 4> InLaneMask;
9716   InLaneMask.resize(LaneSize, -1);
9717   for (int i = 0; i < Size; ++i) {
9718     if (Mask[i] < 0)
9719       continue;
9720
9721     int j = i / LaneSize;
9722
9723     if (Lanes[j] < 0) {
9724       // First entry we've seen for this lane.
9725       Lanes[j] = Mask[i] / LaneSize;
9726     } else if (Lanes[j] != Mask[i] / LaneSize) {
9727       // This doesn't match the lane selected previously!
9728       return SDValue();
9729     }
9730
9731     // Check that within each lane we have a consistent shuffle mask.
9732     int k = i % LaneSize;
9733     if (InLaneMask[k] < 0) {
9734       InLaneMask[k] = Mask[i] % LaneSize;
9735     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9736       // This doesn't fit a repeating in-lane mask.
9737       return SDValue();
9738     }
9739   }
9740
9741   // First shuffle the lanes into place.
9742   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9743                                 VT.getSizeInBits() / 64);
9744   SmallVector<int, 8> LaneMask;
9745   LaneMask.resize(NumLanes * 2, -1);
9746   for (int i = 0; i < NumLanes; ++i)
9747     if (Lanes[i] >= 0) {
9748       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9749       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9750     }
9751
9752   V1 = DAG.getBitcast(LaneVT, V1);
9753   V2 = DAG.getBitcast(LaneVT, V2);
9754   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9755
9756   // Cast it back to the type we actually want.
9757   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9758
9759   // Now do a simple shuffle that isn't lane crossing.
9760   SmallVector<int, 8> NewMask;
9761   NewMask.resize(Size, -1);
9762   for (int i = 0; i < Size; ++i)
9763     if (Mask[i] >= 0)
9764       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9765   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9766          "Must not introduce lane crosses at this point!");
9767
9768   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9769 }
9770
9771 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9772 /// given mask.
9773 ///
9774 /// This returns true if the elements from a particular input are already in the
9775 /// slot required by the given mask and require no permutation.
9776 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9777   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9778   int Size = Mask.size();
9779   for (int i = 0; i < Size; ++i)
9780     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9781       return false;
9782
9783   return true;
9784 }
9785
9786 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9787                                             ArrayRef<int> Mask, SDValue V1,
9788                                             SDValue V2, SelectionDAG &DAG) {
9789
9790   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9791   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9792   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9793   int NumElts = VT.getVectorNumElements();
9794   bool ShufpdMask = true;
9795   bool CommutableMask = true;
9796   unsigned Immediate = 0;
9797   for (int i = 0; i < NumElts; ++i) {
9798     if (Mask[i] < 0)
9799       continue;
9800     int Val = (i & 6) + NumElts * (i & 1);
9801     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9802     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9803       ShufpdMask = false;
9804     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9805       CommutableMask = false;
9806     Immediate |= (Mask[i] % 2) << i;
9807   }
9808   if (ShufpdMask)
9809     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9810                        DAG.getConstant(Immediate, DL, MVT::i8));
9811   if (CommutableMask)
9812     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9813                        DAG.getConstant(Immediate, DL, MVT::i8));
9814   return SDValue();
9815 }
9816
9817 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9818 ///
9819 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9820 /// isn't available.
9821 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9822                                        const X86Subtarget *Subtarget,
9823                                        SelectionDAG &DAG) {
9824   SDLoc DL(Op);
9825   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9826   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9827   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9828   ArrayRef<int> Mask = SVOp->getMask();
9829   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9830
9831   SmallVector<int, 4> WidenedMask;
9832   if (canWidenShuffleElements(Mask, WidenedMask))
9833     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9834                                     DAG);
9835
9836   if (isSingleInputShuffleMask(Mask)) {
9837     // Check for being able to broadcast a single element.
9838     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9839                                                           Mask, Subtarget, DAG))
9840       return Broadcast;
9841
9842     // Use low duplicate instructions for masks that match their pattern.
9843     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9844       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9845
9846     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9847       // Non-half-crossing single input shuffles can be lowerid with an
9848       // interleaved permutation.
9849       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9850                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9851       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9852                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9853     }
9854
9855     // With AVX2 we have direct support for this permutation.
9856     if (Subtarget->hasAVX2())
9857       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9858                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9859
9860     // Otherwise, fall back.
9861     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9862                                                    DAG);
9863   }
9864
9865   // X86 has dedicated unpack instructions that can handle specific blend
9866   // operations: UNPCKH and UNPCKL.
9867   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9868     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9869   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9870     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9871   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9872     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9873   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9874     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9875
9876   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9877                                                 Subtarget, DAG))
9878     return Blend;
9879
9880   // Check if the blend happens to exactly fit that of SHUFPD.
9881   if (SDValue Op =
9882       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9883     return Op;
9884
9885   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9886   // shuffle. However, if we have AVX2 and either inputs are already in place,
9887   // we will be able to shuffle even across lanes the other input in a single
9888   // instruction so skip this pattern.
9889   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9890                                  isShuffleMaskInputInPlace(1, Mask))))
9891     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9892             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9893       return Result;
9894
9895   // If we have AVX2 then we always want to lower with a blend because an v4 we
9896   // can fully permute the elements.
9897   if (Subtarget->hasAVX2())
9898     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9899                                                       Mask, DAG);
9900
9901   // Otherwise fall back on generic lowering.
9902   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9903 }
9904
9905 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9906 ///
9907 /// This routine is only called when we have AVX2 and thus a reasonable
9908 /// instruction set for v4i64 shuffling..
9909 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9910                                        const X86Subtarget *Subtarget,
9911                                        SelectionDAG &DAG) {
9912   SDLoc DL(Op);
9913   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9914   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9915   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9916   ArrayRef<int> Mask = SVOp->getMask();
9917   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9918   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9919
9920   SmallVector<int, 4> WidenedMask;
9921   if (canWidenShuffleElements(Mask, WidenedMask))
9922     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9923                                     DAG);
9924
9925   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9926                                                 Subtarget, DAG))
9927     return Blend;
9928
9929   // Check for being able to broadcast a single element.
9930   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9931                                                         Mask, Subtarget, DAG))
9932     return Broadcast;
9933
9934   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9935   // use lower latency instructions that will operate on both 128-bit lanes.
9936   SmallVector<int, 2> RepeatedMask;
9937   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9938     if (isSingleInputShuffleMask(Mask)) {
9939       int PSHUFDMask[] = {-1, -1, -1, -1};
9940       for (int i = 0; i < 2; ++i)
9941         if (RepeatedMask[i] >= 0) {
9942           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9943           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9944         }
9945       return DAG.getBitcast(
9946           MVT::v4i64,
9947           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9948                       DAG.getBitcast(MVT::v8i32, V1),
9949                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9950     }
9951   }
9952
9953   // AVX2 provides a direct instruction for permuting a single input across
9954   // lanes.
9955   if (isSingleInputShuffleMask(Mask))
9956     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9957                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9958
9959   // Try to use shift instructions.
9960   if (SDValue Shift =
9961           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9962     return Shift;
9963
9964   // Use dedicated unpack instructions for masks that match their pattern.
9965   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9966     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9967   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9968     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9969   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9970     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9971   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9972     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9973
9974   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9975   // shuffle. However, if we have AVX2 and either inputs are already in place,
9976   // we will be able to shuffle even across lanes the other input in a single
9977   // instruction so skip this pattern.
9978   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9979                                  isShuffleMaskInputInPlace(1, Mask))))
9980     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9981             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9982       return Result;
9983
9984   // Otherwise fall back on generic blend lowering.
9985   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9986                                                     Mask, DAG);
9987 }
9988
9989 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9990 ///
9991 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9992 /// isn't available.
9993 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9994                                        const X86Subtarget *Subtarget,
9995                                        SelectionDAG &DAG) {
9996   SDLoc DL(Op);
9997   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9998   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9999   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10000   ArrayRef<int> Mask = SVOp->getMask();
10001   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10002
10003   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10004                                                 Subtarget, DAG))
10005     return Blend;
10006
10007   // Check for being able to broadcast a single element.
10008   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10009                                                         Mask, Subtarget, DAG))
10010     return Broadcast;
10011
10012   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10013   // options to efficiently lower the shuffle.
10014   SmallVector<int, 4> RepeatedMask;
10015   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10016     assert(RepeatedMask.size() == 4 &&
10017            "Repeated masks must be half the mask width!");
10018
10019     // Use even/odd duplicate instructions for masks that match their pattern.
10020     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10021       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10022     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10023       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10024
10025     if (isSingleInputShuffleMask(Mask))
10026       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10027                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10028
10029     // Use dedicated unpack instructions for masks that match their pattern.
10030     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10031       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10032     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10033       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10034     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10035       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10036     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10037       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10038
10039     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10040     // have already handled any direct blends. We also need to squash the
10041     // repeated mask into a simulated v4f32 mask.
10042     for (int i = 0; i < 4; ++i)
10043       if (RepeatedMask[i] >= 8)
10044         RepeatedMask[i] -= 4;
10045     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10046   }
10047
10048   // If we have a single input shuffle with different shuffle patterns in the
10049   // two 128-bit lanes use the variable mask to VPERMILPS.
10050   if (isSingleInputShuffleMask(Mask)) {
10051     SDValue VPermMask[8];
10052     for (int i = 0; i < 8; ++i)
10053       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10054                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10055     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10056       return DAG.getNode(
10057           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10058           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10059
10060     if (Subtarget->hasAVX2())
10061       return DAG.getNode(
10062           X86ISD::VPERMV, DL, MVT::v8f32,
10063           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10064                                                  MVT::v8i32, VPermMask)),
10065           V1);
10066
10067     // Otherwise, fall back.
10068     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10069                                                    DAG);
10070   }
10071
10072   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10073   // shuffle.
10074   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10075           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10076     return Result;
10077
10078   // If we have AVX2 then we always want to lower with a blend because at v8 we
10079   // can fully permute the elements.
10080   if (Subtarget->hasAVX2())
10081     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10082                                                       Mask, DAG);
10083
10084   // Otherwise fall back on generic lowering.
10085   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10086 }
10087
10088 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10089 ///
10090 /// This routine is only called when we have AVX2 and thus a reasonable
10091 /// instruction set for v8i32 shuffling..
10092 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10093                                        const X86Subtarget *Subtarget,
10094                                        SelectionDAG &DAG) {
10095   SDLoc DL(Op);
10096   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10097   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10098   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10099   ArrayRef<int> Mask = SVOp->getMask();
10100   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10101   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10102
10103   // Whenever we can lower this as a zext, that instruction is strictly faster
10104   // than any alternative. It also allows us to fold memory operands into the
10105   // shuffle in many cases.
10106   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10107                                                          Mask, Subtarget, DAG))
10108     return ZExt;
10109
10110   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10111                                                 Subtarget, DAG))
10112     return Blend;
10113
10114   // Check for being able to broadcast a single element.
10115   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10116                                                         Mask, Subtarget, DAG))
10117     return Broadcast;
10118
10119   // If the shuffle mask is repeated in each 128-bit lane we can use more
10120   // efficient instructions that mirror the shuffles across the two 128-bit
10121   // lanes.
10122   SmallVector<int, 4> RepeatedMask;
10123   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10124     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10125     if (isSingleInputShuffleMask(Mask))
10126       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10127                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10128
10129     // Use dedicated unpack instructions for masks that match their pattern.
10130     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10131       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10132     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10133       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10134     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10135       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10136     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10137       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10138   }
10139
10140   // Try to use shift instructions.
10141   if (SDValue Shift =
10142           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10143     return Shift;
10144
10145   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10146           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10147     return Rotate;
10148
10149   // If the shuffle patterns aren't repeated but it is a single input, directly
10150   // generate a cross-lane VPERMD instruction.
10151   if (isSingleInputShuffleMask(Mask)) {
10152     SDValue VPermMask[8];
10153     for (int i = 0; i < 8; ++i)
10154       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10155                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10156     return DAG.getNode(
10157         X86ISD::VPERMV, DL, MVT::v8i32,
10158         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10159   }
10160
10161   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10162   // shuffle.
10163   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10164           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10165     return Result;
10166
10167   // Otherwise fall back on generic blend lowering.
10168   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10169                                                     Mask, DAG);
10170 }
10171
10172 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10173 ///
10174 /// This routine is only called when we have AVX2 and thus a reasonable
10175 /// instruction set for v16i16 shuffling..
10176 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10177                                         const X86Subtarget *Subtarget,
10178                                         SelectionDAG &DAG) {
10179   SDLoc DL(Op);
10180   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10181   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10182   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10183   ArrayRef<int> Mask = SVOp->getMask();
10184   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10185   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10186
10187   // Whenever we can lower this as a zext, that instruction is strictly faster
10188   // than any alternative. It also allows us to fold memory operands into the
10189   // shuffle in many cases.
10190   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10191                                                          Mask, Subtarget, DAG))
10192     return ZExt;
10193
10194   // Check for being able to broadcast a single element.
10195   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10196                                                         Mask, Subtarget, DAG))
10197     return Broadcast;
10198
10199   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10200                                                 Subtarget, DAG))
10201     return Blend;
10202
10203   // Use dedicated unpack instructions for masks that match their pattern.
10204   if (isShuffleEquivalent(V1, V2, Mask,
10205                           {// First 128-bit lane:
10206                            0, 16, 1, 17, 2, 18, 3, 19,
10207                            // Second 128-bit lane:
10208                            8, 24, 9, 25, 10, 26, 11, 27}))
10209     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10210   if (isShuffleEquivalent(V1, V2, Mask,
10211                           {// First 128-bit lane:
10212                            4, 20, 5, 21, 6, 22, 7, 23,
10213                            // Second 128-bit lane:
10214                            12, 28, 13, 29, 14, 30, 15, 31}))
10215     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10216
10217   // Try to use shift instructions.
10218   if (SDValue Shift =
10219           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10220     return Shift;
10221
10222   // Try to use byte rotation instructions.
10223   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10224           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10225     return Rotate;
10226
10227   if (isSingleInputShuffleMask(Mask)) {
10228     // There are no generalized cross-lane shuffle operations available on i16
10229     // element types.
10230     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10231       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10232                                                      Mask, DAG);
10233
10234     SmallVector<int, 8> RepeatedMask;
10235     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10236       // As this is a single-input shuffle, the repeated mask should be
10237       // a strictly valid v8i16 mask that we can pass through to the v8i16
10238       // lowering to handle even the v16 case.
10239       return lowerV8I16GeneralSingleInputVectorShuffle(
10240           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10241     }
10242
10243     SDValue PSHUFBMask[32];
10244     for (int i = 0; i < 16; ++i) {
10245       if (Mask[i] == -1) {
10246         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10247         continue;
10248       }
10249
10250       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10251       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10252       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10253       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10254     }
10255     return DAG.getBitcast(MVT::v16i16,
10256                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10257                                       DAG.getBitcast(MVT::v32i8, V1),
10258                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10259                                                   MVT::v32i8, PSHUFBMask)));
10260   }
10261
10262   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10263   // shuffle.
10264   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10265           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10266     return Result;
10267
10268   // Otherwise fall back on generic lowering.
10269   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10270 }
10271
10272 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10273 ///
10274 /// This routine is only called when we have AVX2 and thus a reasonable
10275 /// instruction set for v32i8 shuffling..
10276 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10277                                        const X86Subtarget *Subtarget,
10278                                        SelectionDAG &DAG) {
10279   SDLoc DL(Op);
10280   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10281   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10282   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10283   ArrayRef<int> Mask = SVOp->getMask();
10284   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10285   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10286
10287   // Whenever we can lower this as a zext, that instruction is strictly faster
10288   // than any alternative. It also allows us to fold memory operands into the
10289   // shuffle in many cases.
10290   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10291                                                          Mask, Subtarget, DAG))
10292     return ZExt;
10293
10294   // Check for being able to broadcast a single element.
10295   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10296                                                         Mask, Subtarget, DAG))
10297     return Broadcast;
10298
10299   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10300                                                 Subtarget, DAG))
10301     return Blend;
10302
10303   // Use dedicated unpack instructions for masks that match their pattern.
10304   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10305   // 256-bit lanes.
10306   if (isShuffleEquivalent(
10307           V1, V2, Mask,
10308           {// First 128-bit lane:
10309            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10310            // Second 128-bit lane:
10311            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10312     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10313   if (isShuffleEquivalent(
10314           V1, V2, Mask,
10315           {// First 128-bit lane:
10316            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10317            // Second 128-bit lane:
10318            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10319     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10320
10321   // Try to use shift instructions.
10322   if (SDValue Shift =
10323           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10324     return Shift;
10325
10326   // Try to use byte rotation instructions.
10327   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10328           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10329     return Rotate;
10330
10331   if (isSingleInputShuffleMask(Mask)) {
10332     // There are no generalized cross-lane shuffle operations available on i8
10333     // element types.
10334     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10335       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10336                                                      Mask, DAG);
10337
10338     SDValue PSHUFBMask[32];
10339     for (int i = 0; i < 32; ++i)
10340       PSHUFBMask[i] =
10341           Mask[i] < 0
10342               ? DAG.getUNDEF(MVT::i8)
10343               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10344                                 MVT::i8);
10345
10346     return DAG.getNode(
10347         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10348         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10349   }
10350
10351   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10352   // shuffle.
10353   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10354           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10355     return Result;
10356
10357   // Otherwise fall back on generic lowering.
10358   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10359 }
10360
10361 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10362 ///
10363 /// This routine either breaks down the specific type of a 256-bit x86 vector
10364 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10365 /// together based on the available instructions.
10366 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10367                                         MVT VT, const X86Subtarget *Subtarget,
10368                                         SelectionDAG &DAG) {
10369   SDLoc DL(Op);
10370   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10371   ArrayRef<int> Mask = SVOp->getMask();
10372
10373   // If we have a single input to the zero element, insert that into V1 if we
10374   // can do so cheaply.
10375   int NumElts = VT.getVectorNumElements();
10376   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10377     return M >= NumElts;
10378   });
10379
10380   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10381     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10382                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10383       return Insertion;
10384
10385   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10386   // check for those subtargets here and avoid much of the subtarget querying in
10387   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10388   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10389   // floating point types there eventually, just immediately cast everything to
10390   // a float and operate entirely in that domain.
10391   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10392     int ElementBits = VT.getScalarSizeInBits();
10393     if (ElementBits < 32)
10394       // No floating point type available, decompose into 128-bit vectors.
10395       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10396
10397     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10398                                 VT.getVectorNumElements());
10399     V1 = DAG.getBitcast(FpVT, V1);
10400     V2 = DAG.getBitcast(FpVT, V2);
10401     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10402   }
10403
10404   switch (VT.SimpleTy) {
10405   case MVT::v4f64:
10406     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10407   case MVT::v4i64:
10408     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10409   case MVT::v8f32:
10410     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10411   case MVT::v8i32:
10412     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10413   case MVT::v16i16:
10414     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10415   case MVT::v32i8:
10416     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10417
10418   default:
10419     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10420   }
10421 }
10422
10423 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10424 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10425                                        const X86Subtarget *Subtarget,
10426                                        SelectionDAG &DAG) {
10427   SDLoc DL(Op);
10428   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10429   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10430   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10431   ArrayRef<int> Mask = SVOp->getMask();
10432   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10433
10434   // X86 has dedicated unpack instructions that can handle specific blend
10435   // operations: UNPCKH and UNPCKL.
10436   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10437     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10438   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10439     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10440
10441   // FIXME: Implement direct support for this type!
10442   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10443 }
10444
10445 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10446 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10447                                        const X86Subtarget *Subtarget,
10448                                        SelectionDAG &DAG) {
10449   SDLoc DL(Op);
10450   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10451   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10452   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10453   ArrayRef<int> Mask = SVOp->getMask();
10454   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10455
10456   // Use dedicated unpack instructions for masks that match their pattern.
10457   if (isShuffleEquivalent(V1, V2, Mask,
10458                           {// First 128-bit lane.
10459                            0, 16, 1, 17, 4, 20, 5, 21,
10460                            // Second 128-bit lane.
10461                            8, 24, 9, 25, 12, 28, 13, 29}))
10462     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10463   if (isShuffleEquivalent(V1, V2, Mask,
10464                           {// First 128-bit lane.
10465                            2, 18, 3, 19, 6, 22, 7, 23,
10466                            // Second 128-bit lane.
10467                            10, 26, 11, 27, 14, 30, 15, 31}))
10468     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10469
10470   // FIXME: Implement direct support for this type!
10471   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10472 }
10473
10474 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10475 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10476                                        const X86Subtarget *Subtarget,
10477                                        SelectionDAG &DAG) {
10478   SDLoc DL(Op);
10479   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10480   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10481   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10482   ArrayRef<int> Mask = SVOp->getMask();
10483   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10484
10485   // X86 has dedicated unpack instructions that can handle specific blend
10486   // operations: UNPCKH and UNPCKL.
10487   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10488     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10489   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10490     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10491
10492   // FIXME: Implement direct support for this type!
10493   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10494 }
10495
10496 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10497 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10498                                        const X86Subtarget *Subtarget,
10499                                        SelectionDAG &DAG) {
10500   SDLoc DL(Op);
10501   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10502   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10503   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10504   ArrayRef<int> Mask = SVOp->getMask();
10505   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10506
10507   // Use dedicated unpack instructions for masks that match their pattern.
10508   if (isShuffleEquivalent(V1, V2, Mask,
10509                           {// First 128-bit lane.
10510                            0, 16, 1, 17, 4, 20, 5, 21,
10511                            // Second 128-bit lane.
10512                            8, 24, 9, 25, 12, 28, 13, 29}))
10513     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10514   if (isShuffleEquivalent(V1, V2, Mask,
10515                           {// First 128-bit lane.
10516                            2, 18, 3, 19, 6, 22, 7, 23,
10517                            // Second 128-bit lane.
10518                            10, 26, 11, 27, 14, 30, 15, 31}))
10519     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10520
10521   // FIXME: Implement direct support for this type!
10522   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10523 }
10524
10525 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10526 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10527                                         const X86Subtarget *Subtarget,
10528                                         SelectionDAG &DAG) {
10529   SDLoc DL(Op);
10530   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10531   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10532   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10533   ArrayRef<int> Mask = SVOp->getMask();
10534   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10535   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10536
10537   // FIXME: Implement direct support for this type!
10538   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10539 }
10540
10541 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10542 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10543                                        const X86Subtarget *Subtarget,
10544                                        SelectionDAG &DAG) {
10545   SDLoc DL(Op);
10546   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10547   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10548   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10549   ArrayRef<int> Mask = SVOp->getMask();
10550   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10551   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10552
10553   // FIXME: Implement direct support for this type!
10554   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10555 }
10556
10557 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10558 ///
10559 /// This routine either breaks down the specific type of a 512-bit x86 vector
10560 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10561 /// together based on the available instructions.
10562 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10563                                         MVT VT, const X86Subtarget *Subtarget,
10564                                         SelectionDAG &DAG) {
10565   SDLoc DL(Op);
10566   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10567   ArrayRef<int> Mask = SVOp->getMask();
10568   assert(Subtarget->hasAVX512() &&
10569          "Cannot lower 512-bit vectors w/ basic ISA!");
10570
10571   // Check for being able to broadcast a single element.
10572   if (SDValue Broadcast =
10573           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10574     return Broadcast;
10575
10576   // Dispatch to each element type for lowering. If we don't have supprot for
10577   // specific element type shuffles at 512 bits, immediately split them and
10578   // lower them. Each lowering routine of a given type is allowed to assume that
10579   // the requisite ISA extensions for that element type are available.
10580   switch (VT.SimpleTy) {
10581   case MVT::v8f64:
10582     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10583   case MVT::v16f32:
10584     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10585   case MVT::v8i64:
10586     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10587   case MVT::v16i32:
10588     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10589   case MVT::v32i16:
10590     if (Subtarget->hasBWI())
10591       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10592     break;
10593   case MVT::v64i8:
10594     if (Subtarget->hasBWI())
10595       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10596     break;
10597
10598   default:
10599     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10600   }
10601
10602   // Otherwise fall back on splitting.
10603   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10604 }
10605
10606 /// \brief Top-level lowering for x86 vector shuffles.
10607 ///
10608 /// This handles decomposition, canonicalization, and lowering of all x86
10609 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10610 /// above in helper routines. The canonicalization attempts to widen shuffles
10611 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10612 /// s.t. only one of the two inputs needs to be tested, etc.
10613 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10614                                   SelectionDAG &DAG) {
10615   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10616   ArrayRef<int> Mask = SVOp->getMask();
10617   SDValue V1 = Op.getOperand(0);
10618   SDValue V2 = Op.getOperand(1);
10619   MVT VT = Op.getSimpleValueType();
10620   int NumElements = VT.getVectorNumElements();
10621   SDLoc dl(Op);
10622
10623   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10624
10625   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10626   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10627   if (V1IsUndef && V2IsUndef)
10628     return DAG.getUNDEF(VT);
10629
10630   // When we create a shuffle node we put the UNDEF node to second operand,
10631   // but in some cases the first operand may be transformed to UNDEF.
10632   // In this case we should just commute the node.
10633   if (V1IsUndef)
10634     return DAG.getCommutedVectorShuffle(*SVOp);
10635
10636   // Check for non-undef masks pointing at an undef vector and make the masks
10637   // undef as well. This makes it easier to match the shuffle based solely on
10638   // the mask.
10639   if (V2IsUndef)
10640     for (int M : Mask)
10641       if (M >= NumElements) {
10642         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10643         for (int &M : NewMask)
10644           if (M >= NumElements)
10645             M = -1;
10646         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10647       }
10648
10649   // We actually see shuffles that are entirely re-arrangements of a set of
10650   // zero inputs. This mostly happens while decomposing complex shuffles into
10651   // simple ones. Directly lower these as a buildvector of zeros.
10652   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10653   if (Zeroable.all())
10654     return getZeroVector(VT, Subtarget, DAG, dl);
10655
10656   // Try to collapse shuffles into using a vector type with fewer elements but
10657   // wider element types. We cap this to not form integers or floating point
10658   // elements wider than 64 bits, but it might be interesting to form i128
10659   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10660   SmallVector<int, 16> WidenedMask;
10661   if (VT.getScalarSizeInBits() < 64 &&
10662       canWidenShuffleElements(Mask, WidenedMask)) {
10663     MVT NewEltVT = VT.isFloatingPoint()
10664                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10665                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10666     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10667     // Make sure that the new vector type is legal. For example, v2f64 isn't
10668     // legal on SSE1.
10669     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10670       V1 = DAG.getBitcast(NewVT, V1);
10671       V2 = DAG.getBitcast(NewVT, V2);
10672       return DAG.getBitcast(
10673           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10674     }
10675   }
10676
10677   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10678   for (int M : SVOp->getMask())
10679     if (M < 0)
10680       ++NumUndefElements;
10681     else if (M < NumElements)
10682       ++NumV1Elements;
10683     else
10684       ++NumV2Elements;
10685
10686   // Commute the shuffle as needed such that more elements come from V1 than
10687   // V2. This allows us to match the shuffle pattern strictly on how many
10688   // elements come from V1 without handling the symmetric cases.
10689   if (NumV2Elements > NumV1Elements)
10690     return DAG.getCommutedVectorShuffle(*SVOp);
10691
10692   // When the number of V1 and V2 elements are the same, try to minimize the
10693   // number of uses of V2 in the low half of the vector. When that is tied,
10694   // ensure that the sum of indices for V1 is equal to or lower than the sum
10695   // indices for V2. When those are equal, try to ensure that the number of odd
10696   // indices for V1 is lower than the number of odd indices for V2.
10697   if (NumV1Elements == NumV2Elements) {
10698     int LowV1Elements = 0, LowV2Elements = 0;
10699     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10700       if (M >= NumElements)
10701         ++LowV2Elements;
10702       else if (M >= 0)
10703         ++LowV1Elements;
10704     if (LowV2Elements > LowV1Elements) {
10705       return DAG.getCommutedVectorShuffle(*SVOp);
10706     } else if (LowV2Elements == LowV1Elements) {
10707       int SumV1Indices = 0, SumV2Indices = 0;
10708       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10709         if (SVOp->getMask()[i] >= NumElements)
10710           SumV2Indices += i;
10711         else if (SVOp->getMask()[i] >= 0)
10712           SumV1Indices += i;
10713       if (SumV2Indices < SumV1Indices) {
10714         return DAG.getCommutedVectorShuffle(*SVOp);
10715       } else if (SumV2Indices == SumV1Indices) {
10716         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10717         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10718           if (SVOp->getMask()[i] >= NumElements)
10719             NumV2OddIndices += i % 2;
10720           else if (SVOp->getMask()[i] >= 0)
10721             NumV1OddIndices += i % 2;
10722         if (NumV2OddIndices < NumV1OddIndices)
10723           return DAG.getCommutedVectorShuffle(*SVOp);
10724       }
10725     }
10726   }
10727
10728   // For each vector width, delegate to a specialized lowering routine.
10729   if (VT.getSizeInBits() == 128)
10730     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10731
10732   if (VT.getSizeInBits() == 256)
10733     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10734
10735   // Force AVX-512 vectors to be scalarized for now.
10736   // FIXME: Implement AVX-512 support!
10737   if (VT.getSizeInBits() == 512)
10738     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10739
10740   llvm_unreachable("Unimplemented!");
10741 }
10742
10743 // This function assumes its argument is a BUILD_VECTOR of constants or
10744 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10745 // true.
10746 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10747                                     unsigned &MaskValue) {
10748   MaskValue = 0;
10749   unsigned NumElems = BuildVector->getNumOperands();
10750   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10751   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10752   unsigned NumElemsInLane = NumElems / NumLanes;
10753
10754   // Blend for v16i16 should be symmetric for the both lanes.
10755   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10756     SDValue EltCond = BuildVector->getOperand(i);
10757     SDValue SndLaneEltCond =
10758         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10759
10760     int Lane1Cond = -1, Lane2Cond = -1;
10761     if (isa<ConstantSDNode>(EltCond))
10762       Lane1Cond = !isZero(EltCond);
10763     if (isa<ConstantSDNode>(SndLaneEltCond))
10764       Lane2Cond = !isZero(SndLaneEltCond);
10765
10766     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10767       // Lane1Cond != 0, means we want the first argument.
10768       // Lane1Cond == 0, means we want the second argument.
10769       // The encoding of this argument is 0 for the first argument, 1
10770       // for the second. Therefore, invert the condition.
10771       MaskValue |= !Lane1Cond << i;
10772     else if (Lane1Cond < 0)
10773       MaskValue |= !Lane2Cond << i;
10774     else
10775       return false;
10776   }
10777   return true;
10778 }
10779
10780 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10781 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10782                                            const X86Subtarget *Subtarget,
10783                                            SelectionDAG &DAG) {
10784   SDValue Cond = Op.getOperand(0);
10785   SDValue LHS = Op.getOperand(1);
10786   SDValue RHS = Op.getOperand(2);
10787   SDLoc dl(Op);
10788   MVT VT = Op.getSimpleValueType();
10789
10790   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10791     return SDValue();
10792   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10793
10794   // Only non-legal VSELECTs reach this lowering, convert those into generic
10795   // shuffles and re-use the shuffle lowering path for blends.
10796   SmallVector<int, 32> Mask;
10797   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10798     SDValue CondElt = CondBV->getOperand(i);
10799     Mask.push_back(
10800         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10801   }
10802   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10803 }
10804
10805 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10806   // A vselect where all conditions and data are constants can be optimized into
10807   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10808   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10809       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10810       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10811     return SDValue();
10812
10813   // Try to lower this to a blend-style vector shuffle. This can handle all
10814   // constant condition cases.
10815   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10816     return BlendOp;
10817
10818   // Variable blends are only legal from SSE4.1 onward.
10819   if (!Subtarget->hasSSE41())
10820     return SDValue();
10821
10822   // Only some types will be legal on some subtargets. If we can emit a legal
10823   // VSELECT-matching blend, return Op, and but if we need to expand, return
10824   // a null value.
10825   switch (Op.getSimpleValueType().SimpleTy) {
10826   default:
10827     // Most of the vector types have blends past SSE4.1.
10828     return Op;
10829
10830   case MVT::v32i8:
10831     // The byte blends for AVX vectors were introduced only in AVX2.
10832     if (Subtarget->hasAVX2())
10833       return Op;
10834
10835     return SDValue();
10836
10837   case MVT::v8i16:
10838   case MVT::v16i16:
10839     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10840     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10841       return Op;
10842
10843     // FIXME: We should custom lower this by fixing the condition and using i8
10844     // blends.
10845     return SDValue();
10846   }
10847 }
10848
10849 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10850   MVT VT = Op.getSimpleValueType();
10851   SDLoc dl(Op);
10852
10853   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10854     return SDValue();
10855
10856   if (VT.getSizeInBits() == 8) {
10857     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10858                                   Op.getOperand(0), Op.getOperand(1));
10859     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10860                                   DAG.getValueType(VT));
10861     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10862   }
10863
10864   if (VT.getSizeInBits() == 16) {
10865     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10866     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10867     if (Idx == 0)
10868       return DAG.getNode(
10869           ISD::TRUNCATE, dl, MVT::i16,
10870           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10871                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10872                       Op.getOperand(1)));
10873     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10874                                   Op.getOperand(0), Op.getOperand(1));
10875     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10876                                   DAG.getValueType(VT));
10877     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10878   }
10879
10880   if (VT == MVT::f32) {
10881     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10882     // the result back to FR32 register. It's only worth matching if the
10883     // result has a single use which is a store or a bitcast to i32.  And in
10884     // the case of a store, it's not worth it if the index is a constant 0,
10885     // because a MOVSSmr can be used instead, which is smaller and faster.
10886     if (!Op.hasOneUse())
10887       return SDValue();
10888     SDNode *User = *Op.getNode()->use_begin();
10889     if ((User->getOpcode() != ISD::STORE ||
10890          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10891           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10892         (User->getOpcode() != ISD::BITCAST ||
10893          User->getValueType(0) != MVT::i32))
10894       return SDValue();
10895     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10896                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10897                                   Op.getOperand(1));
10898     return DAG.getBitcast(MVT::f32, Extract);
10899   }
10900
10901   if (VT == MVT::i32 || VT == MVT::i64) {
10902     // ExtractPS/pextrq works with constant index.
10903     if (isa<ConstantSDNode>(Op.getOperand(1)))
10904       return Op;
10905   }
10906   return SDValue();
10907 }
10908
10909 /// Extract one bit from mask vector, like v16i1 or v8i1.
10910 /// AVX-512 feature.
10911 SDValue
10912 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10913   SDValue Vec = Op.getOperand(0);
10914   SDLoc dl(Vec);
10915   MVT VecVT = Vec.getSimpleValueType();
10916   SDValue Idx = Op.getOperand(1);
10917   MVT EltVT = Op.getSimpleValueType();
10918
10919   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10920   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10921          "Unexpected vector type in ExtractBitFromMaskVector");
10922
10923   // variable index can't be handled in mask registers,
10924   // extend vector to VR512
10925   if (!isa<ConstantSDNode>(Idx)) {
10926     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10927     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10928     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10929                               ExtVT.getVectorElementType(), Ext, Idx);
10930     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10931   }
10932
10933   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10934   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10935   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10936     rc = getRegClassFor(MVT::v16i1);
10937   unsigned MaxSift = rc->getSize()*8 - 1;
10938   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10939                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10940   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10941                     DAG.getConstant(MaxSift, dl, MVT::i8));
10942   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10943                        DAG.getIntPtrConstant(0, dl));
10944 }
10945
10946 SDValue
10947 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10948                                            SelectionDAG &DAG) const {
10949   SDLoc dl(Op);
10950   SDValue Vec = Op.getOperand(0);
10951   MVT VecVT = Vec.getSimpleValueType();
10952   SDValue Idx = Op.getOperand(1);
10953
10954   if (Op.getSimpleValueType() == MVT::i1)
10955     return ExtractBitFromMaskVector(Op, DAG);
10956
10957   if (!isa<ConstantSDNode>(Idx)) {
10958     if (VecVT.is512BitVector() ||
10959         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10960          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10961
10962       MVT MaskEltVT =
10963         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10964       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10965                                     MaskEltVT.getSizeInBits());
10966
10967       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10968       auto PtrVT = getPointerTy(DAG.getDataLayout());
10969       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10970                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10971                                  DAG.getConstant(0, dl, PtrVT));
10972       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10973       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10974                          DAG.getConstant(0, dl, PtrVT));
10975     }
10976     return SDValue();
10977   }
10978
10979   // If this is a 256-bit vector result, first extract the 128-bit vector and
10980   // then extract the element from the 128-bit vector.
10981   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10982
10983     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10984     // Get the 128-bit vector.
10985     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10986     MVT EltVT = VecVT.getVectorElementType();
10987
10988     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10989
10990     //if (IdxVal >= NumElems/2)
10991     //  IdxVal -= NumElems/2;
10992     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10993     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10994                        DAG.getConstant(IdxVal, dl, MVT::i32));
10995   }
10996
10997   assert(VecVT.is128BitVector() && "Unexpected vector length");
10998
10999   if (Subtarget->hasSSE41())
11000     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11001       return Res;
11002
11003   MVT VT = Op.getSimpleValueType();
11004   // TODO: handle v16i8.
11005   if (VT.getSizeInBits() == 16) {
11006     SDValue Vec = Op.getOperand(0);
11007     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11008     if (Idx == 0)
11009       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11010                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11011                                      DAG.getBitcast(MVT::v4i32, Vec),
11012                                      Op.getOperand(1)));
11013     // Transform it so it match pextrw which produces a 32-bit result.
11014     MVT EltVT = MVT::i32;
11015     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11016                                   Op.getOperand(0), Op.getOperand(1));
11017     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11018                                   DAG.getValueType(VT));
11019     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11020   }
11021
11022   if (VT.getSizeInBits() == 32) {
11023     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11024     if (Idx == 0)
11025       return Op;
11026
11027     // SHUFPS the element to the lowest double word, then movss.
11028     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11029     MVT VVT = Op.getOperand(0).getSimpleValueType();
11030     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11031                                        DAG.getUNDEF(VVT), Mask);
11032     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11033                        DAG.getIntPtrConstant(0, dl));
11034   }
11035
11036   if (VT.getSizeInBits() == 64) {
11037     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11038     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11039     //        to match extract_elt for f64.
11040     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11041     if (Idx == 0)
11042       return Op;
11043
11044     // UNPCKHPD the element to the lowest double word, then movsd.
11045     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11046     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11047     int Mask[2] = { 1, -1 };
11048     MVT VVT = Op.getOperand(0).getSimpleValueType();
11049     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11050                                        DAG.getUNDEF(VVT), Mask);
11051     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11052                        DAG.getIntPtrConstant(0, dl));
11053   }
11054
11055   return SDValue();
11056 }
11057
11058 /// Insert one bit to mask vector, like v16i1 or v8i1.
11059 /// AVX-512 feature.
11060 SDValue
11061 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11062   SDLoc dl(Op);
11063   SDValue Vec = Op.getOperand(0);
11064   SDValue Elt = Op.getOperand(1);
11065   SDValue Idx = Op.getOperand(2);
11066   MVT VecVT = Vec.getSimpleValueType();
11067
11068   if (!isa<ConstantSDNode>(Idx)) {
11069     // Non constant index. Extend source and destination,
11070     // insert element and then truncate the result.
11071     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11072     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11073     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11074       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11075       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11076     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11077   }
11078
11079   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11080   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11081   if (IdxVal)
11082     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11083                            DAG.getConstant(IdxVal, dl, MVT::i8));
11084   if (Vec.getOpcode() == ISD::UNDEF)
11085     return EltInVec;
11086   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11087 }
11088
11089 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11090                                                   SelectionDAG &DAG) const {
11091   MVT VT = Op.getSimpleValueType();
11092   MVT EltVT = VT.getVectorElementType();
11093
11094   if (EltVT == MVT::i1)
11095     return InsertBitToMaskVector(Op, DAG);
11096
11097   SDLoc dl(Op);
11098   SDValue N0 = Op.getOperand(0);
11099   SDValue N1 = Op.getOperand(1);
11100   SDValue N2 = Op.getOperand(2);
11101   if (!isa<ConstantSDNode>(N2))
11102     return SDValue();
11103   auto *N2C = cast<ConstantSDNode>(N2);
11104   unsigned IdxVal = N2C->getZExtValue();
11105
11106   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11107   // into that, and then insert the subvector back into the result.
11108   if (VT.is256BitVector() || VT.is512BitVector()) {
11109     // With a 256-bit vector, we can insert into the zero element efficiently
11110     // using a blend if we have AVX or AVX2 and the right data type.
11111     if (VT.is256BitVector() && IdxVal == 0) {
11112       // TODO: It is worthwhile to cast integer to floating point and back
11113       // and incur a domain crossing penalty if that's what we'll end up
11114       // doing anyway after extracting to a 128-bit vector.
11115       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11116           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11117         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11118         N2 = DAG.getIntPtrConstant(1, dl);
11119         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11120       }
11121     }
11122
11123     // Get the desired 128-bit vector chunk.
11124     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11125
11126     // Insert the element into the desired chunk.
11127     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11128     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11129
11130     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11131                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11132
11133     // Insert the changed part back into the bigger vector
11134     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11135   }
11136   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11137
11138   if (Subtarget->hasSSE41()) {
11139     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11140       unsigned Opc;
11141       if (VT == MVT::v8i16) {
11142         Opc = X86ISD::PINSRW;
11143       } else {
11144         assert(VT == MVT::v16i8);
11145         Opc = X86ISD::PINSRB;
11146       }
11147
11148       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11149       // argument.
11150       if (N1.getValueType() != MVT::i32)
11151         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11152       if (N2.getValueType() != MVT::i32)
11153         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11154       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11155     }
11156
11157     if (EltVT == MVT::f32) {
11158       // Bits [7:6] of the constant are the source select. This will always be
11159       //   zero here. The DAG Combiner may combine an extract_elt index into
11160       //   these bits. For example (insert (extract, 3), 2) could be matched by
11161       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11162       // Bits [5:4] of the constant are the destination select. This is the
11163       //   value of the incoming immediate.
11164       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11165       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11166
11167       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11168       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11169         // If this is an insertion of 32-bits into the low 32-bits of
11170         // a vector, we prefer to generate a blend with immediate rather
11171         // than an insertps. Blends are simpler operations in hardware and so
11172         // will always have equal or better performance than insertps.
11173         // But if optimizing for size and there's a load folding opportunity,
11174         // generate insertps because blendps does not have a 32-bit memory
11175         // operand form.
11176         N2 = DAG.getIntPtrConstant(1, dl);
11177         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11178         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11179       }
11180       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11181       // Create this as a scalar to vector..
11182       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11183       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11184     }
11185
11186     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11187       // PINSR* works with constant index.
11188       return Op;
11189     }
11190   }
11191
11192   if (EltVT == MVT::i8)
11193     return SDValue();
11194
11195   if (EltVT.getSizeInBits() == 16) {
11196     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11197     // as its second argument.
11198     if (N1.getValueType() != MVT::i32)
11199       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11200     if (N2.getValueType() != MVT::i32)
11201       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11202     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11203   }
11204   return SDValue();
11205 }
11206
11207 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11208   SDLoc dl(Op);
11209   MVT OpVT = Op.getSimpleValueType();
11210
11211   // If this is a 256-bit vector result, first insert into a 128-bit
11212   // vector and then insert into the 256-bit vector.
11213   if (!OpVT.is128BitVector()) {
11214     // Insert into a 128-bit vector.
11215     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11216     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11217                                  OpVT.getVectorNumElements() / SizeFactor);
11218
11219     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11220
11221     // Insert the 128-bit vector.
11222     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11223   }
11224
11225   if (OpVT == MVT::v1i64 &&
11226       Op.getOperand(0).getValueType() == MVT::i64)
11227     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11228
11229   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11230   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11231   return DAG.getBitcast(
11232       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11233 }
11234
11235 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11236 // a simple subregister reference or explicit instructions to grab
11237 // upper bits of a vector.
11238 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11239                                       SelectionDAG &DAG) {
11240   SDLoc dl(Op);
11241   SDValue In =  Op.getOperand(0);
11242   SDValue Idx = Op.getOperand(1);
11243   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11244   MVT ResVT   = Op.getSimpleValueType();
11245   MVT InVT    = In.getSimpleValueType();
11246
11247   if (Subtarget->hasFp256()) {
11248     if (ResVT.is128BitVector() &&
11249         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11250         isa<ConstantSDNode>(Idx)) {
11251       return Extract128BitVector(In, IdxVal, DAG, dl);
11252     }
11253     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11254         isa<ConstantSDNode>(Idx)) {
11255       return Extract256BitVector(In, IdxVal, DAG, dl);
11256     }
11257   }
11258   return SDValue();
11259 }
11260
11261 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11262 // simple superregister reference or explicit instructions to insert
11263 // the upper bits of a vector.
11264 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11265                                      SelectionDAG &DAG) {
11266   if (!Subtarget->hasAVX())
11267     return SDValue();
11268
11269   SDLoc dl(Op);
11270   SDValue Vec = Op.getOperand(0);
11271   SDValue SubVec = Op.getOperand(1);
11272   SDValue Idx = Op.getOperand(2);
11273
11274   if (!isa<ConstantSDNode>(Idx))
11275     return SDValue();
11276
11277   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11278   MVT OpVT = Op.getSimpleValueType();
11279   MVT SubVecVT = SubVec.getSimpleValueType();
11280
11281   // Fold two 16-byte subvector loads into one 32-byte load:
11282   // (insert_subvector (insert_subvector undef, (load addr), 0),
11283   //                   (load addr + 16), Elts/2)
11284   // --> load32 addr
11285   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11286       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11287       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11288     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11289     if (Idx2 && Idx2->getZExtValue() == 0) {
11290       SDValue SubVec2 = Vec.getOperand(1);
11291       // If needed, look through a bitcast to get to the load.
11292       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11293         SubVec2 = SubVec2.getOperand(0);
11294       
11295       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11296         bool Fast;
11297         unsigned Alignment = FirstLd->getAlignment();
11298         unsigned AS = FirstLd->getAddressSpace();
11299         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11300         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11301                                     OpVT, AS, Alignment, &Fast) && Fast) {
11302           SDValue Ops[] = { SubVec2, SubVec };
11303           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11304             return Ld;
11305         }
11306       }
11307     }
11308   }
11309
11310   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11311       SubVecVT.is128BitVector())
11312     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11313
11314   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11315     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11316
11317   if (OpVT.getVectorElementType() == MVT::i1) {
11318     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11319       return Op;
11320     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11321     SDValue Undef = DAG.getUNDEF(OpVT);
11322     unsigned NumElems = OpVT.getVectorNumElements();
11323     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11324
11325     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11326       // Zero upper bits of the Vec
11327       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11328       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11329
11330       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11331                                  SubVec, ZeroIdx);
11332       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11333       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11334     }
11335     if (IdxVal == 0) {
11336       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11337                                  SubVec, ZeroIdx);
11338       // Zero upper bits of the Vec2
11339       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11340       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11341       // Zero lower bits of the Vec
11342       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11343       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11344       // Merge them together
11345       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11346     }
11347   }
11348   return SDValue();
11349 }
11350
11351 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11352 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11353 // one of the above mentioned nodes. It has to be wrapped because otherwise
11354 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11355 // be used to form addressing mode. These wrapped nodes will be selected
11356 // into MOV32ri.
11357 SDValue
11358 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11359   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11360
11361   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11362   // global base reg.
11363   unsigned char OpFlag = 0;
11364   unsigned WrapperKind = X86ISD::Wrapper;
11365   CodeModel::Model M = DAG.getTarget().getCodeModel();
11366
11367   if (Subtarget->isPICStyleRIPRel() &&
11368       (M == CodeModel::Small || M == CodeModel::Kernel))
11369     WrapperKind = X86ISD::WrapperRIP;
11370   else if (Subtarget->isPICStyleGOT())
11371     OpFlag = X86II::MO_GOTOFF;
11372   else if (Subtarget->isPICStyleStubPIC())
11373     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11374
11375   auto PtrVT = getPointerTy(DAG.getDataLayout());
11376   SDValue Result = DAG.getTargetConstantPool(
11377       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11378   SDLoc DL(CP);
11379   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11380   // With PIC, the address is actually $g + Offset.
11381   if (OpFlag) {
11382     Result =
11383         DAG.getNode(ISD::ADD, DL, PtrVT,
11384                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11385   }
11386
11387   return Result;
11388 }
11389
11390 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11391   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11392
11393   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11394   // global base reg.
11395   unsigned char OpFlag = 0;
11396   unsigned WrapperKind = X86ISD::Wrapper;
11397   CodeModel::Model M = DAG.getTarget().getCodeModel();
11398
11399   if (Subtarget->isPICStyleRIPRel() &&
11400       (M == CodeModel::Small || M == CodeModel::Kernel))
11401     WrapperKind = X86ISD::WrapperRIP;
11402   else if (Subtarget->isPICStyleGOT())
11403     OpFlag = X86II::MO_GOTOFF;
11404   else if (Subtarget->isPICStyleStubPIC())
11405     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11406
11407   auto PtrVT = getPointerTy(DAG.getDataLayout());
11408   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11409   SDLoc DL(JT);
11410   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11411
11412   // With PIC, the address is actually $g + Offset.
11413   if (OpFlag)
11414     Result =
11415         DAG.getNode(ISD::ADD, DL, PtrVT,
11416                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11417
11418   return Result;
11419 }
11420
11421 SDValue
11422 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11423   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11424
11425   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11426   // global base reg.
11427   unsigned char OpFlag = 0;
11428   unsigned WrapperKind = X86ISD::Wrapper;
11429   CodeModel::Model M = DAG.getTarget().getCodeModel();
11430
11431   if (Subtarget->isPICStyleRIPRel() &&
11432       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11433     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11434       OpFlag = X86II::MO_GOTPCREL;
11435     WrapperKind = X86ISD::WrapperRIP;
11436   } else if (Subtarget->isPICStyleGOT()) {
11437     OpFlag = X86II::MO_GOT;
11438   } else if (Subtarget->isPICStyleStubPIC()) {
11439     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11440   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11441     OpFlag = X86II::MO_DARWIN_NONLAZY;
11442   }
11443
11444   auto PtrVT = getPointerTy(DAG.getDataLayout());
11445   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11446
11447   SDLoc DL(Op);
11448   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11449
11450   // With PIC, the address is actually $g + Offset.
11451   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11452       !Subtarget->is64Bit()) {
11453     Result =
11454         DAG.getNode(ISD::ADD, DL, PtrVT,
11455                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11456   }
11457
11458   // For symbols that require a load from a stub to get the address, emit the
11459   // load.
11460   if (isGlobalStubReference(OpFlag))
11461     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11462                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11463                          false, false, false, 0);
11464
11465   return Result;
11466 }
11467
11468 SDValue
11469 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11470   // Create the TargetBlockAddressAddress node.
11471   unsigned char OpFlags =
11472     Subtarget->ClassifyBlockAddressReference();
11473   CodeModel::Model M = DAG.getTarget().getCodeModel();
11474   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11475   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11476   SDLoc dl(Op);
11477   auto PtrVT = getPointerTy(DAG.getDataLayout());
11478   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11479
11480   if (Subtarget->isPICStyleRIPRel() &&
11481       (M == CodeModel::Small || M == CodeModel::Kernel))
11482     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11483   else
11484     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11485
11486   // With PIC, the address is actually $g + Offset.
11487   if (isGlobalRelativeToPICBase(OpFlags)) {
11488     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11489                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11490   }
11491
11492   return Result;
11493 }
11494
11495 SDValue
11496 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11497                                       int64_t Offset, SelectionDAG &DAG) const {
11498   // Create the TargetGlobalAddress node, folding in the constant
11499   // offset if it is legal.
11500   unsigned char OpFlags =
11501       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11502   CodeModel::Model M = DAG.getTarget().getCodeModel();
11503   auto PtrVT = getPointerTy(DAG.getDataLayout());
11504   SDValue Result;
11505   if (OpFlags == X86II::MO_NO_FLAG &&
11506       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11507     // A direct static reference to a global.
11508     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11509     Offset = 0;
11510   } else {
11511     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11512   }
11513
11514   if (Subtarget->isPICStyleRIPRel() &&
11515       (M == CodeModel::Small || M == CodeModel::Kernel))
11516     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11517   else
11518     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11519
11520   // With PIC, the address is actually $g + Offset.
11521   if (isGlobalRelativeToPICBase(OpFlags)) {
11522     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11523                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11524   }
11525
11526   // For globals that require a load from a stub to get the address, emit the
11527   // load.
11528   if (isGlobalStubReference(OpFlags))
11529     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11530                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11531                          false, false, false, 0);
11532
11533   // If there was a non-zero offset that we didn't fold, create an explicit
11534   // addition for it.
11535   if (Offset != 0)
11536     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11537                          DAG.getConstant(Offset, dl, PtrVT));
11538
11539   return Result;
11540 }
11541
11542 SDValue
11543 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11544   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11545   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11546   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11547 }
11548
11549 static SDValue
11550 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11551            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11552            unsigned char OperandFlags, bool LocalDynamic = false) {
11553   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11554   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11555   SDLoc dl(GA);
11556   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11557                                            GA->getValueType(0),
11558                                            GA->getOffset(),
11559                                            OperandFlags);
11560
11561   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11562                                            : X86ISD::TLSADDR;
11563
11564   if (InFlag) {
11565     SDValue Ops[] = { Chain,  TGA, *InFlag };
11566     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11567   } else {
11568     SDValue Ops[]  = { Chain, TGA };
11569     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11570   }
11571
11572   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11573   MFI->setAdjustsStack(true);
11574   MFI->setHasCalls(true);
11575
11576   SDValue Flag = Chain.getValue(1);
11577   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11578 }
11579
11580 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11581 static SDValue
11582 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11583                                 const EVT PtrVT) {
11584   SDValue InFlag;
11585   SDLoc dl(GA);  // ? function entry point might be better
11586   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11587                                    DAG.getNode(X86ISD::GlobalBaseReg,
11588                                                SDLoc(), PtrVT), InFlag);
11589   InFlag = Chain.getValue(1);
11590
11591   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11592 }
11593
11594 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11595 static SDValue
11596 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11597                                 const EVT PtrVT) {
11598   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11599                     X86::RAX, X86II::MO_TLSGD);
11600 }
11601
11602 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11603                                            SelectionDAG &DAG,
11604                                            const EVT PtrVT,
11605                                            bool is64Bit) {
11606   SDLoc dl(GA);
11607
11608   // Get the start address of the TLS block for this module.
11609   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11610       .getInfo<X86MachineFunctionInfo>();
11611   MFI->incNumLocalDynamicTLSAccesses();
11612
11613   SDValue Base;
11614   if (is64Bit) {
11615     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11616                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11617   } else {
11618     SDValue InFlag;
11619     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11620         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11621     InFlag = Chain.getValue(1);
11622     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11623                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11624   }
11625
11626   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11627   // of Base.
11628
11629   // Build x@dtpoff.
11630   unsigned char OperandFlags = X86II::MO_DTPOFF;
11631   unsigned WrapperKind = X86ISD::Wrapper;
11632   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11633                                            GA->getValueType(0),
11634                                            GA->getOffset(), OperandFlags);
11635   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11636
11637   // Add x@dtpoff with the base.
11638   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11639 }
11640
11641 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11642 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11643                                    const EVT PtrVT, TLSModel::Model model,
11644                                    bool is64Bit, bool isPIC) {
11645   SDLoc dl(GA);
11646
11647   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11648   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11649                                                          is64Bit ? 257 : 256));
11650
11651   SDValue ThreadPointer =
11652       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11653                   MachinePointerInfo(Ptr), false, false, false, 0);
11654
11655   unsigned char OperandFlags = 0;
11656   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11657   // initialexec.
11658   unsigned WrapperKind = X86ISD::Wrapper;
11659   if (model == TLSModel::LocalExec) {
11660     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11661   } else if (model == TLSModel::InitialExec) {
11662     if (is64Bit) {
11663       OperandFlags = X86II::MO_GOTTPOFF;
11664       WrapperKind = X86ISD::WrapperRIP;
11665     } else {
11666       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11667     }
11668   } else {
11669     llvm_unreachable("Unexpected model");
11670   }
11671
11672   // emit "addl x@ntpoff,%eax" (local exec)
11673   // or "addl x@indntpoff,%eax" (initial exec)
11674   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11675   SDValue TGA =
11676       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11677                                  GA->getOffset(), OperandFlags);
11678   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11679
11680   if (model == TLSModel::InitialExec) {
11681     if (isPIC && !is64Bit) {
11682       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11683                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11684                            Offset);
11685     }
11686
11687     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11688                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11689                          false, false, false, 0);
11690   }
11691
11692   // The address of the thread local variable is the add of the thread
11693   // pointer with the offset of the variable.
11694   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11695 }
11696
11697 SDValue
11698 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11699
11700   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11701   const GlobalValue *GV = GA->getGlobal();
11702   auto PtrVT = getPointerTy(DAG.getDataLayout());
11703
11704   if (Subtarget->isTargetELF()) {
11705     if (DAG.getTarget().Options.EmulatedTLS)
11706       return LowerToTLSEmulatedModel(GA, DAG);
11707     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11708     switch (model) {
11709       case TLSModel::GeneralDynamic:
11710         if (Subtarget->is64Bit())
11711           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11712         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11713       case TLSModel::LocalDynamic:
11714         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11715                                            Subtarget->is64Bit());
11716       case TLSModel::InitialExec:
11717       case TLSModel::LocalExec:
11718         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11719                                    DAG.getTarget().getRelocationModel() ==
11720                                        Reloc::PIC_);
11721     }
11722     llvm_unreachable("Unknown TLS model.");
11723   }
11724
11725   if (Subtarget->isTargetDarwin()) {
11726     // Darwin only has one model of TLS.  Lower to that.
11727     unsigned char OpFlag = 0;
11728     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11729                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11730
11731     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11732     // global base reg.
11733     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11734                  !Subtarget->is64Bit();
11735     if (PIC32)
11736       OpFlag = X86II::MO_TLVP_PIC_BASE;
11737     else
11738       OpFlag = X86II::MO_TLVP;
11739     SDLoc DL(Op);
11740     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11741                                                 GA->getValueType(0),
11742                                                 GA->getOffset(), OpFlag);
11743     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11744
11745     // With PIC32, the address is actually $g + Offset.
11746     if (PIC32)
11747       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11748                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11749                            Offset);
11750
11751     // Lowering the machine isd will make sure everything is in the right
11752     // location.
11753     SDValue Chain = DAG.getEntryNode();
11754     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11755     SDValue Args[] = { Chain, Offset };
11756     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11757
11758     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11759     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11760     MFI->setAdjustsStack(true);
11761
11762     // And our return value (tls address) is in the standard call return value
11763     // location.
11764     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11765     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11766   }
11767
11768   if (Subtarget->isTargetKnownWindowsMSVC() ||
11769       Subtarget->isTargetWindowsGNU()) {
11770     // Just use the implicit TLS architecture
11771     // Need to generate someting similar to:
11772     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11773     //                                  ; from TEB
11774     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11775     //   mov     rcx, qword [rdx+rcx*8]
11776     //   mov     eax, .tls$:tlsvar
11777     //   [rax+rcx] contains the address
11778     // Windows 64bit: gs:0x58
11779     // Windows 32bit: fs:__tls_array
11780
11781     SDLoc dl(GA);
11782     SDValue Chain = DAG.getEntryNode();
11783
11784     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11785     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11786     // use its literal value of 0x2C.
11787     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11788                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11789                                                              256)
11790                                         : Type::getInt32PtrTy(*DAG.getContext(),
11791                                                               257));
11792
11793     SDValue TlsArray = Subtarget->is64Bit()
11794                            ? DAG.getIntPtrConstant(0x58, dl)
11795                            : (Subtarget->isTargetWindowsGNU()
11796                                   ? DAG.getIntPtrConstant(0x2C, dl)
11797                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11798
11799     SDValue ThreadPointer =
11800         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11801                     false, false, 0);
11802
11803     SDValue res;
11804     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11805       res = ThreadPointer;
11806     } else {
11807       // Load the _tls_index variable
11808       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11809       if (Subtarget->is64Bit())
11810         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11811                              MachinePointerInfo(), MVT::i32, false, false,
11812                              false, 0);
11813       else
11814         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11815                           false, false, 0);
11816
11817       auto &DL = DAG.getDataLayout();
11818       SDValue Scale =
11819           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11820       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11821
11822       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11823     }
11824
11825     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11826                       false, 0);
11827
11828     // Get the offset of start of .tls section
11829     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11830                                              GA->getValueType(0),
11831                                              GA->getOffset(), X86II::MO_SECREL);
11832     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11833
11834     // The address of the thread local variable is the add of the thread
11835     // pointer with the offset of the variable.
11836     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11837   }
11838
11839   llvm_unreachable("TLS not implemented for this target.");
11840 }
11841
11842 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11843 /// and take a 2 x i32 value to shift plus a shift amount.
11844 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11845   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11846   MVT VT = Op.getSimpleValueType();
11847   unsigned VTBits = VT.getSizeInBits();
11848   SDLoc dl(Op);
11849   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11850   SDValue ShOpLo = Op.getOperand(0);
11851   SDValue ShOpHi = Op.getOperand(1);
11852   SDValue ShAmt  = Op.getOperand(2);
11853   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11854   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11855   // during isel.
11856   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11857                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11858   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11859                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11860                        : DAG.getConstant(0, dl, VT);
11861
11862   SDValue Tmp2, Tmp3;
11863   if (Op.getOpcode() == ISD::SHL_PARTS) {
11864     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11865     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11866   } else {
11867     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11868     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11869   }
11870
11871   // If the shift amount is larger or equal than the width of a part we can't
11872   // rely on the results of shld/shrd. Insert a test and select the appropriate
11873   // values for large shift amounts.
11874   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11875                                 DAG.getConstant(VTBits, dl, MVT::i8));
11876   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11877                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11878
11879   SDValue Hi, Lo;
11880   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11881   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11882   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11883
11884   if (Op.getOpcode() == ISD::SHL_PARTS) {
11885     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11886     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11887   } else {
11888     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11889     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11890   }
11891
11892   SDValue Ops[2] = { Lo, Hi };
11893   return DAG.getMergeValues(Ops, dl);
11894 }
11895
11896 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11897                                            SelectionDAG &DAG) const {
11898   SDValue Src = Op.getOperand(0);
11899   MVT SrcVT = Src.getSimpleValueType();
11900   MVT VT = Op.getSimpleValueType();
11901   SDLoc dl(Op);
11902
11903   if (SrcVT.isVector()) {
11904     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11905       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11906                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11907                          DAG.getUNDEF(SrcVT)));
11908     }
11909     if (SrcVT.getVectorElementType() == MVT::i1) {
11910       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11911       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11912                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11913     }
11914     return SDValue();
11915   }
11916
11917   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11918          "Unknown SINT_TO_FP to lower!");
11919
11920   // These are really Legal; return the operand so the caller accepts it as
11921   // Legal.
11922   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11923     return Op;
11924   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11925       Subtarget->is64Bit()) {
11926     return Op;
11927   }
11928
11929   unsigned Size = SrcVT.getSizeInBits()/8;
11930   MachineFunction &MF = DAG.getMachineFunction();
11931   auto PtrVT = getPointerTy(MF.getDataLayout());
11932   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11933   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11934   SDValue Chain = DAG.getStore(
11935       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11936       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11937       false, 0);
11938   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11939 }
11940
11941 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11942                                      SDValue StackSlot,
11943                                      SelectionDAG &DAG) const {
11944   // Build the FILD
11945   SDLoc DL(Op);
11946   SDVTList Tys;
11947   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11948   if (useSSE)
11949     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11950   else
11951     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11952
11953   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11954
11955   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11956   MachineMemOperand *MMO;
11957   if (FI) {
11958     int SSFI = FI->getIndex();
11959     MMO = DAG.getMachineFunction().getMachineMemOperand(
11960         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11961         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11962   } else {
11963     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11964     StackSlot = StackSlot.getOperand(1);
11965   }
11966   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11967   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11968                                            X86ISD::FILD, DL,
11969                                            Tys, Ops, SrcVT, MMO);
11970
11971   if (useSSE) {
11972     Chain = Result.getValue(1);
11973     SDValue InFlag = Result.getValue(2);
11974
11975     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11976     // shouldn't be necessary except that RFP cannot be live across
11977     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11978     MachineFunction &MF = DAG.getMachineFunction();
11979     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11980     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11981     auto PtrVT = getPointerTy(MF.getDataLayout());
11982     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11983     Tys = DAG.getVTList(MVT::Other);
11984     SDValue Ops[] = {
11985       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11986     };
11987     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11988         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11989         MachineMemOperand::MOStore, SSFISize, SSFISize);
11990
11991     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11992                                     Ops, Op.getValueType(), MMO);
11993     Result = DAG.getLoad(
11994         Op.getValueType(), DL, Chain, StackSlot,
11995         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11996         false, false, false, 0);
11997   }
11998
11999   return Result;
12000 }
12001
12002 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12003 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12004                                                SelectionDAG &DAG) const {
12005   // This algorithm is not obvious. Here it is what we're trying to output:
12006   /*
12007      movq       %rax,  %xmm0
12008      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12009      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12010      #ifdef __SSE3__
12011        haddpd   %xmm0, %xmm0
12012      #else
12013        pshufd   $0x4e, %xmm0, %xmm1
12014        addpd    %xmm1, %xmm0
12015      #endif
12016   */
12017
12018   SDLoc dl(Op);
12019   LLVMContext *Context = DAG.getContext();
12020
12021   // Build some magic constants.
12022   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12023   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12024   auto PtrVT = getPointerTy(DAG.getDataLayout());
12025   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12026
12027   SmallVector<Constant*,2> CV1;
12028   CV1.push_back(
12029     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12030                                       APInt(64, 0x4330000000000000ULL))));
12031   CV1.push_back(
12032     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12033                                       APInt(64, 0x4530000000000000ULL))));
12034   Constant *C1 = ConstantVector::get(CV1);
12035   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12036
12037   // Load the 64-bit value into an XMM register.
12038   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12039                             Op.getOperand(0));
12040   SDValue CLod0 =
12041       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12042                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12043                   false, false, false, 16);
12044   SDValue Unpck1 =
12045       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12046
12047   SDValue CLod1 =
12048       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12049                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12050                   false, false, false, 16);
12051   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12052   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12053   SDValue Result;
12054
12055   if (Subtarget->hasSSE3()) {
12056     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12057     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12058   } else {
12059     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12060     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12061                                            S2F, 0x4E, DAG);
12062     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12063                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12064   }
12065
12066   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12067                      DAG.getIntPtrConstant(0, dl));
12068 }
12069
12070 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12071 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12072                                                SelectionDAG &DAG) const {
12073   SDLoc dl(Op);
12074   // FP constant to bias correct the final result.
12075   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12076                                    MVT::f64);
12077
12078   // Load the 32-bit value into an XMM register.
12079   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12080                              Op.getOperand(0));
12081
12082   // Zero out the upper parts of the register.
12083   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12084
12085   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12086                      DAG.getBitcast(MVT::v2f64, Load),
12087                      DAG.getIntPtrConstant(0, dl));
12088
12089   // Or the load with the bias.
12090   SDValue Or = DAG.getNode(
12091       ISD::OR, dl, MVT::v2i64,
12092       DAG.getBitcast(MVT::v2i64,
12093                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12094       DAG.getBitcast(MVT::v2i64,
12095                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12096   Or =
12097       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12098                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12099
12100   // Subtract the bias.
12101   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12102
12103   // Handle final rounding.
12104   EVT DestVT = Op.getValueType();
12105
12106   if (DestVT.bitsLT(MVT::f64))
12107     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12108                        DAG.getIntPtrConstant(0, dl));
12109   if (DestVT.bitsGT(MVT::f64))
12110     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12111
12112   // Handle final rounding.
12113   return Sub;
12114 }
12115
12116 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12117                                      const X86Subtarget &Subtarget) {
12118   // The algorithm is the following:
12119   // #ifdef __SSE4_1__
12120   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12121   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12122   //                                 (uint4) 0x53000000, 0xaa);
12123   // #else
12124   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12125   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12126   // #endif
12127   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12128   //     return (float4) lo + fhi;
12129
12130   SDLoc DL(Op);
12131   SDValue V = Op->getOperand(0);
12132   EVT VecIntVT = V.getValueType();
12133   bool Is128 = VecIntVT == MVT::v4i32;
12134   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12135   // If we convert to something else than the supported type, e.g., to v4f64,
12136   // abort early.
12137   if (VecFloatVT != Op->getValueType(0))
12138     return SDValue();
12139
12140   unsigned NumElts = VecIntVT.getVectorNumElements();
12141   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12142          "Unsupported custom type");
12143   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12144
12145   // In the #idef/#else code, we have in common:
12146   // - The vector of constants:
12147   // -- 0x4b000000
12148   // -- 0x53000000
12149   // - A shift:
12150   // -- v >> 16
12151
12152   // Create the splat vector for 0x4b000000.
12153   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12154   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12155                            CstLow, CstLow, CstLow, CstLow};
12156   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12157                                   makeArrayRef(&CstLowArray[0], NumElts));
12158   // Create the splat vector for 0x53000000.
12159   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12160   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12161                             CstHigh, CstHigh, CstHigh, CstHigh};
12162   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12163                                    makeArrayRef(&CstHighArray[0], NumElts));
12164
12165   // Create the right shift.
12166   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12167   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12168                              CstShift, CstShift, CstShift, CstShift};
12169   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12170                                     makeArrayRef(&CstShiftArray[0], NumElts));
12171   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12172
12173   SDValue Low, High;
12174   if (Subtarget.hasSSE41()) {
12175     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12176     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12177     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12178     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12179     // Low will be bitcasted right away, so do not bother bitcasting back to its
12180     // original type.
12181     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12182                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12183     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12184     //                                 (uint4) 0x53000000, 0xaa);
12185     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12186     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12187     // High will be bitcasted right away, so do not bother bitcasting back to
12188     // its original type.
12189     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12190                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12191   } else {
12192     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12193     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12194                                      CstMask, CstMask, CstMask);
12195     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12196     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12197     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12198
12199     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12200     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12201   }
12202
12203   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12204   SDValue CstFAdd = DAG.getConstantFP(
12205       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12206   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12207                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12208   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12209                                    makeArrayRef(&CstFAddArray[0], NumElts));
12210
12211   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12212   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12213   SDValue FHigh =
12214       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12215   //     return (float4) lo + fhi;
12216   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12217   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12218 }
12219
12220 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12221                                                SelectionDAG &DAG) const {
12222   SDValue N0 = Op.getOperand(0);
12223   MVT SVT = N0.getSimpleValueType();
12224   SDLoc dl(Op);
12225
12226   switch (SVT.SimpleTy) {
12227   default:
12228     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12229   case MVT::v4i8:
12230   case MVT::v4i16:
12231   case MVT::v8i8:
12232   case MVT::v8i16: {
12233     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12234     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12235                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12236   }
12237   case MVT::v4i32:
12238   case MVT::v8i32:
12239     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12240   case MVT::v16i8:
12241   case MVT::v16i16:
12242     if (Subtarget->hasAVX512())
12243       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12244                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12245   }
12246   llvm_unreachable(nullptr);
12247 }
12248
12249 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12250                                            SelectionDAG &DAG) const {
12251   SDValue N0 = Op.getOperand(0);
12252   SDLoc dl(Op);
12253   auto PtrVT = getPointerTy(DAG.getDataLayout());
12254
12255   if (Op.getValueType().isVector())
12256     return lowerUINT_TO_FP_vec(Op, DAG);
12257
12258   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12259   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12260   // the optimization here.
12261   if (DAG.SignBitIsZero(N0))
12262     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12263
12264   MVT SrcVT = N0.getSimpleValueType();
12265   MVT DstVT = Op.getSimpleValueType();
12266   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12267     return LowerUINT_TO_FP_i64(Op, DAG);
12268   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12269     return LowerUINT_TO_FP_i32(Op, DAG);
12270   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12271     return SDValue();
12272
12273   // Make a 64-bit buffer, and use it to build an FILD.
12274   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12275   if (SrcVT == MVT::i32) {
12276     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12277     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12278     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12279                                   StackSlot, MachinePointerInfo(),
12280                                   false, false, 0);
12281     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12282                                   OffsetSlot, MachinePointerInfo(),
12283                                   false, false, 0);
12284     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12285     return Fild;
12286   }
12287
12288   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12289   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12290                                StackSlot, MachinePointerInfo(),
12291                                false, false, 0);
12292   // For i64 source, we need to add the appropriate power of 2 if the input
12293   // was negative.  This is the same as the optimization in
12294   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12295   // we must be careful to do the computation in x87 extended precision, not
12296   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12297   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12298   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12299       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12300       MachineMemOperand::MOLoad, 8, 8);
12301
12302   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12303   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12304   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12305                                          MVT::i64, MMO);
12306
12307   APInt FF(32, 0x5F800000ULL);
12308
12309   // Check whether the sign bit is set.
12310   SDValue SignSet = DAG.getSetCC(
12311       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12312       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12313
12314   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12315   SDValue FudgePtr = DAG.getConstantPool(
12316       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12317
12318   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12319   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12320   SDValue Four = DAG.getIntPtrConstant(4, dl);
12321   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12322                                Zero, Four);
12323   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12324
12325   // Load the value out, extending it from f32 to f80.
12326   // FIXME: Avoid the extend by constructing the right constant pool?
12327   SDValue Fudge = DAG.getExtLoad(
12328       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12329       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12330       false, false, false, 4);
12331   // Extend everything to 80 bits to force it to be done on x87.
12332   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12333   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12334                      DAG.getIntPtrConstant(0, dl));
12335 }
12336
12337 std::pair<SDValue,SDValue>
12338 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12339                                     bool IsSigned, bool IsReplace) const {
12340   SDLoc DL(Op);
12341
12342   EVT DstTy = Op.getValueType();
12343   auto PtrVT = getPointerTy(DAG.getDataLayout());
12344
12345   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12346     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12347     DstTy = MVT::i64;
12348   }
12349
12350   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12351          DstTy.getSimpleVT() >= MVT::i16 &&
12352          "Unknown FP_TO_INT to lower!");
12353
12354   // These are really Legal.
12355   if (DstTy == MVT::i32 &&
12356       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12357     return std::make_pair(SDValue(), SDValue());
12358   if (Subtarget->is64Bit() &&
12359       DstTy == MVT::i64 &&
12360       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12361     return std::make_pair(SDValue(), SDValue());
12362
12363   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12364   // stack slot, or into the FTOL runtime function.
12365   MachineFunction &MF = DAG.getMachineFunction();
12366   unsigned MemSize = DstTy.getSizeInBits()/8;
12367   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12368   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12369
12370   unsigned Opc;
12371   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12372     Opc = X86ISD::WIN_FTOL;
12373   else
12374     switch (DstTy.getSimpleVT().SimpleTy) {
12375     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12376     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12377     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12378     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12379     }
12380
12381   SDValue Chain = DAG.getEntryNode();
12382   SDValue Value = Op.getOperand(0);
12383   EVT TheVT = Op.getOperand(0).getValueType();
12384   // FIXME This causes a redundant load/store if the SSE-class value is already
12385   // in memory, such as if it is on the callstack.
12386   if (isScalarFPTypeInSSEReg(TheVT)) {
12387     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12388     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12389                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12390                          false, 0);
12391     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12392     SDValue Ops[] = {
12393       Chain, StackSlot, DAG.getValueType(TheVT)
12394     };
12395
12396     MachineMemOperand *MMO =
12397         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12398                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12399     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12400     Chain = Value.getValue(1);
12401     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12402     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12403   }
12404
12405   MachineMemOperand *MMO =
12406       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12407                               MachineMemOperand::MOStore, MemSize, MemSize);
12408
12409   if (Opc != X86ISD::WIN_FTOL) {
12410     // Build the FP_TO_INT*_IN_MEM
12411     SDValue Ops[] = { Chain, Value, StackSlot };
12412     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12413                                            Ops, DstTy, MMO);
12414     return std::make_pair(FIST, StackSlot);
12415   } else {
12416     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12417       DAG.getVTList(MVT::Other, MVT::Glue),
12418       Chain, Value);
12419     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12420       MVT::i32, ftol.getValue(1));
12421     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12422       MVT::i32, eax.getValue(2));
12423     SDValue Ops[] = { eax, edx };
12424     SDValue pair = IsReplace
12425       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12426       : DAG.getMergeValues(Ops, DL);
12427     return std::make_pair(pair, SDValue());
12428   }
12429 }
12430
12431 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12432                               const X86Subtarget *Subtarget) {
12433   MVT VT = Op->getSimpleValueType(0);
12434   SDValue In = Op->getOperand(0);
12435   MVT InVT = In.getSimpleValueType();
12436   SDLoc dl(Op);
12437
12438   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12439     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12440
12441   // Optimize vectors in AVX mode:
12442   //
12443   //   v8i16 -> v8i32
12444   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12445   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12446   //   Concat upper and lower parts.
12447   //
12448   //   v4i32 -> v4i64
12449   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12450   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12451   //   Concat upper and lower parts.
12452   //
12453
12454   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12455       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12456       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12457     return SDValue();
12458
12459   if (Subtarget->hasInt256())
12460     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12461
12462   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12463   SDValue Undef = DAG.getUNDEF(InVT);
12464   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12465   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12466   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12467
12468   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12469                              VT.getVectorNumElements()/2);
12470
12471   OpLo = DAG.getBitcast(HVT, OpLo);
12472   OpHi = DAG.getBitcast(HVT, OpHi);
12473
12474   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12475 }
12476
12477 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12478                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12479   MVT VT = Op->getSimpleValueType(0);
12480   SDValue In = Op->getOperand(0);
12481   MVT InVT = In.getSimpleValueType();
12482   SDLoc DL(Op);
12483   unsigned int NumElts = VT.getVectorNumElements();
12484   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12485     return SDValue();
12486
12487   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12488     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12489
12490   assert(InVT.getVectorElementType() == MVT::i1);
12491   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12492   SDValue One =
12493    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12494   SDValue Zero =
12495    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12496
12497   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12498   if (VT.is512BitVector())
12499     return V;
12500   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12501 }
12502
12503 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12504                                SelectionDAG &DAG) {
12505   if (Subtarget->hasFp256())
12506     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12507       return Res;
12508
12509   return SDValue();
12510 }
12511
12512 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12513                                 SelectionDAG &DAG) {
12514   SDLoc DL(Op);
12515   MVT VT = Op.getSimpleValueType();
12516   SDValue In = Op.getOperand(0);
12517   MVT SVT = In.getSimpleValueType();
12518
12519   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12520     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12521
12522   if (Subtarget->hasFp256())
12523     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12524       return Res;
12525
12526   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12527          VT.getVectorNumElements() != SVT.getVectorNumElements());
12528   return SDValue();
12529 }
12530
12531 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12532   SDLoc DL(Op);
12533   MVT VT = Op.getSimpleValueType();
12534   SDValue In = Op.getOperand(0);
12535   MVT InVT = In.getSimpleValueType();
12536
12537   if (VT == MVT::i1) {
12538     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12539            "Invalid scalar TRUNCATE operation");
12540     if (InVT.getSizeInBits() >= 32)
12541       return SDValue();
12542     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12543     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12544   }
12545   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12546          "Invalid TRUNCATE operation");
12547
12548   // move vector to mask - truncate solution for SKX
12549   if (VT.getVectorElementType() == MVT::i1) {
12550     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12551         Subtarget->hasBWI())
12552       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12553     if ((InVT.is256BitVector() || InVT.is128BitVector())
12554         && InVT.getScalarSizeInBits() <= 16 &&
12555         Subtarget->hasBWI() && Subtarget->hasVLX())
12556       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12557     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12558         Subtarget->hasDQI())
12559       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12560     if ((InVT.is256BitVector() || InVT.is128BitVector())
12561         && InVT.getScalarSizeInBits() >= 32 &&
12562         Subtarget->hasDQI() && Subtarget->hasVLX())
12563       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12564   }
12565
12566   if (VT.getVectorElementType() == MVT::i1) {
12567     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12568     unsigned NumElts = InVT.getVectorNumElements();
12569     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12570     if (InVT.getSizeInBits() < 512) {
12571       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12572       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12573       InVT = ExtVT;
12574     }
12575
12576     SDValue OneV =
12577      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12578     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12579     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12580   }
12581
12582   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12583   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12584       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12585     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12586
12587   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12588     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12589     if (Subtarget->hasInt256()) {
12590       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12591       In = DAG.getBitcast(MVT::v8i32, In);
12592       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12593                                 ShufMask);
12594       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12595                          DAG.getIntPtrConstant(0, DL));
12596     }
12597
12598     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12599                                DAG.getIntPtrConstant(0, DL));
12600     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12601                                DAG.getIntPtrConstant(2, DL));
12602     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12603     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12604     static const int ShufMask[] = {0, 2, 4, 6};
12605     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12606   }
12607
12608   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12609     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12610     if (Subtarget->hasInt256()) {
12611       In = DAG.getBitcast(MVT::v32i8, In);
12612
12613       SmallVector<SDValue,32> pshufbMask;
12614       for (unsigned i = 0; i < 2; ++i) {
12615         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12616         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12617         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12618         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12619         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12620         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12621         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12622         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12623         for (unsigned j = 0; j < 8; ++j)
12624           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12625       }
12626       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12627       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12628       In = DAG.getBitcast(MVT::v4i64, In);
12629
12630       static const int ShufMask[] = {0,  2,  -1,  -1};
12631       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12632                                 &ShufMask[0]);
12633       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12634                        DAG.getIntPtrConstant(0, DL));
12635       return DAG.getBitcast(VT, In);
12636     }
12637
12638     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12639                                DAG.getIntPtrConstant(0, DL));
12640
12641     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12642                                DAG.getIntPtrConstant(4, DL));
12643
12644     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12645     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12646
12647     // The PSHUFB mask:
12648     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12649                                    -1, -1, -1, -1, -1, -1, -1, -1};
12650
12651     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12652     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12653     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12654
12655     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12656     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12657
12658     // The MOVLHPS Mask:
12659     static const int ShufMask2[] = {0, 1, 4, 5};
12660     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12661     return DAG.getBitcast(MVT::v8i16, res);
12662   }
12663
12664   // Handle truncation of V256 to V128 using shuffles.
12665   if (!VT.is128BitVector() || !InVT.is256BitVector())
12666     return SDValue();
12667
12668   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12669
12670   unsigned NumElems = VT.getVectorNumElements();
12671   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12672
12673   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12674   // Prepare truncation shuffle mask
12675   for (unsigned i = 0; i != NumElems; ++i)
12676     MaskVec[i] = i * 2;
12677   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12678                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12679   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12680                      DAG.getIntPtrConstant(0, DL));
12681 }
12682
12683 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12684                                            SelectionDAG &DAG) const {
12685   assert(!Op.getSimpleValueType().isVector());
12686
12687   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12688     /*IsSigned=*/ true, /*IsReplace=*/ false);
12689   SDValue FIST = Vals.first, StackSlot = Vals.second;
12690   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12691   if (!FIST.getNode()) return Op;
12692
12693   if (StackSlot.getNode())
12694     // Load the result.
12695     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12696                        FIST, StackSlot, MachinePointerInfo(),
12697                        false, false, false, 0);
12698
12699   // The node is the result.
12700   return FIST;
12701 }
12702
12703 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12704                                            SelectionDAG &DAG) const {
12705   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12706     /*IsSigned=*/ false, /*IsReplace=*/ false);
12707   SDValue FIST = Vals.first, StackSlot = Vals.second;
12708   assert(FIST.getNode() && "Unexpected failure");
12709
12710   if (StackSlot.getNode())
12711     // Load the result.
12712     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12713                        FIST, StackSlot, MachinePointerInfo(),
12714                        false, false, false, 0);
12715
12716   // The node is the result.
12717   return FIST;
12718 }
12719
12720 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12721   SDLoc DL(Op);
12722   MVT VT = Op.getSimpleValueType();
12723   SDValue In = Op.getOperand(0);
12724   MVT SVT = In.getSimpleValueType();
12725
12726   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12727
12728   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12729                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12730                                  In, DAG.getUNDEF(SVT)));
12731 }
12732
12733 /// The only differences between FABS and FNEG are the mask and the logic op.
12734 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12735 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12736   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12737          "Wrong opcode for lowering FABS or FNEG.");
12738
12739   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12740
12741   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12742   // into an FNABS. We'll lower the FABS after that if it is still in use.
12743   if (IsFABS)
12744     for (SDNode *User : Op->uses())
12745       if (User->getOpcode() == ISD::FNEG)
12746         return Op;
12747
12748   SDLoc dl(Op);
12749   MVT VT = Op.getSimpleValueType();
12750
12751   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12752   // decide if we should generate a 16-byte constant mask when we only need 4 or
12753   // 8 bytes for the scalar case.
12754
12755   MVT LogicVT;
12756   MVT EltVT;
12757   unsigned NumElts;
12758
12759   if (VT.isVector()) {
12760     LogicVT = VT;
12761     EltVT = VT.getVectorElementType();
12762     NumElts = VT.getVectorNumElements();
12763   } else {
12764     // There are no scalar bitwise logical SSE/AVX instructions, so we
12765     // generate a 16-byte vector constant and logic op even for the scalar case.
12766     // Using a 16-byte mask allows folding the load of the mask with
12767     // the logic op, so it can save (~4 bytes) on code size.
12768     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12769     EltVT = VT;
12770     NumElts = (VT == MVT::f64) ? 2 : 4;
12771   }
12772
12773   unsigned EltBits = EltVT.getSizeInBits();
12774   LLVMContext *Context = DAG.getContext();
12775   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12776   APInt MaskElt =
12777     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12778   Constant *C = ConstantInt::get(*Context, MaskElt);
12779   C = ConstantVector::getSplat(NumElts, C);
12780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12781   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12782   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12783   SDValue Mask =
12784       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12785                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12786                   false, false, false, Alignment);
12787
12788   SDValue Op0 = Op.getOperand(0);
12789   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12790   unsigned LogicOp =
12791     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12792   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12793
12794   if (VT.isVector())
12795     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12796
12797   // For the scalar case extend to a 128-bit vector, perform the logic op,
12798   // and extract the scalar result back out.
12799   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12800   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12801   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12802                      DAG.getIntPtrConstant(0, dl));
12803 }
12804
12805 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12806   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12807   LLVMContext *Context = DAG.getContext();
12808   SDValue Op0 = Op.getOperand(0);
12809   SDValue Op1 = Op.getOperand(1);
12810   SDLoc dl(Op);
12811   MVT VT = Op.getSimpleValueType();
12812   MVT SrcVT = Op1.getSimpleValueType();
12813
12814   // If second operand is smaller, extend it first.
12815   if (SrcVT.bitsLT(VT)) {
12816     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12817     SrcVT = VT;
12818   }
12819   // And if it is bigger, shrink it first.
12820   if (SrcVT.bitsGT(VT)) {
12821     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12822     SrcVT = VT;
12823   }
12824
12825   // At this point the operands and the result should have the same
12826   // type, and that won't be f80 since that is not custom lowered.
12827
12828   const fltSemantics &Sem =
12829       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12830   const unsigned SizeInBits = VT.getSizeInBits();
12831
12832   SmallVector<Constant *, 4> CV(
12833       VT == MVT::f64 ? 2 : 4,
12834       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12835
12836   // First, clear all bits but the sign bit from the second operand (sign).
12837   CV[0] = ConstantFP::get(*Context,
12838                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12839   Constant *C = ConstantVector::get(CV);
12840   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12841   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12842
12843   // Perform all logic operations as 16-byte vectors because there are no
12844   // scalar FP logic instructions in SSE. This allows load folding of the
12845   // constants into the logic instructions.
12846   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12847   SDValue Mask1 =
12848       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12849                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12850                   false, false, false, 16);
12851   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12852   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12853
12854   // Next, clear the sign bit from the first operand (magnitude).
12855   // If it's a constant, we can clear it here.
12856   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12857     APFloat APF = Op0CN->getValueAPF();
12858     // If the magnitude is a positive zero, the sign bit alone is enough.
12859     if (APF.isPosZero())
12860       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12861                          DAG.getIntPtrConstant(0, dl));
12862     APF.clearSign();
12863     CV[0] = ConstantFP::get(*Context, APF);
12864   } else {
12865     CV[0] = ConstantFP::get(
12866         *Context,
12867         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12868   }
12869   C = ConstantVector::get(CV);
12870   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12871   SDValue Val =
12872       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12873                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12874                   false, false, false, 16);
12875   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12876   if (!isa<ConstantFPSDNode>(Op0)) {
12877     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12878     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12879   }
12880   // OR the magnitude value with the sign bit.
12881   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12882   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12883                      DAG.getIntPtrConstant(0, dl));
12884 }
12885
12886 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12887   SDValue N0 = Op.getOperand(0);
12888   SDLoc dl(Op);
12889   MVT VT = Op.getSimpleValueType();
12890
12891   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12892   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12893                                   DAG.getConstant(1, dl, VT));
12894   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12895 }
12896
12897 // Check whether an OR'd tree is PTEST-able.
12898 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12899                                       SelectionDAG &DAG) {
12900   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12901
12902   if (!Subtarget->hasSSE41())
12903     return SDValue();
12904
12905   if (!Op->hasOneUse())
12906     return SDValue();
12907
12908   SDNode *N = Op.getNode();
12909   SDLoc DL(N);
12910
12911   SmallVector<SDValue, 8> Opnds;
12912   DenseMap<SDValue, unsigned> VecInMap;
12913   SmallVector<SDValue, 8> VecIns;
12914   EVT VT = MVT::Other;
12915
12916   // Recognize a special case where a vector is casted into wide integer to
12917   // test all 0s.
12918   Opnds.push_back(N->getOperand(0));
12919   Opnds.push_back(N->getOperand(1));
12920
12921   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12922     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12923     // BFS traverse all OR'd operands.
12924     if (I->getOpcode() == ISD::OR) {
12925       Opnds.push_back(I->getOperand(0));
12926       Opnds.push_back(I->getOperand(1));
12927       // Re-evaluate the number of nodes to be traversed.
12928       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12929       continue;
12930     }
12931
12932     // Quit if a non-EXTRACT_VECTOR_ELT
12933     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12934       return SDValue();
12935
12936     // Quit if without a constant index.
12937     SDValue Idx = I->getOperand(1);
12938     if (!isa<ConstantSDNode>(Idx))
12939       return SDValue();
12940
12941     SDValue ExtractedFromVec = I->getOperand(0);
12942     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12943     if (M == VecInMap.end()) {
12944       VT = ExtractedFromVec.getValueType();
12945       // Quit if not 128/256-bit vector.
12946       if (!VT.is128BitVector() && !VT.is256BitVector())
12947         return SDValue();
12948       // Quit if not the same type.
12949       if (VecInMap.begin() != VecInMap.end() &&
12950           VT != VecInMap.begin()->first.getValueType())
12951         return SDValue();
12952       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12953       VecIns.push_back(ExtractedFromVec);
12954     }
12955     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12956   }
12957
12958   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12959          "Not extracted from 128-/256-bit vector.");
12960
12961   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12962
12963   for (DenseMap<SDValue, unsigned>::const_iterator
12964         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12965     // Quit if not all elements are used.
12966     if (I->second != FullMask)
12967       return SDValue();
12968   }
12969
12970   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12971
12972   // Cast all vectors into TestVT for PTEST.
12973   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12974     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12975
12976   // If more than one full vectors are evaluated, OR them first before PTEST.
12977   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12978     // Each iteration will OR 2 nodes and append the result until there is only
12979     // 1 node left, i.e. the final OR'd value of all vectors.
12980     SDValue LHS = VecIns[Slot];
12981     SDValue RHS = VecIns[Slot + 1];
12982     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12983   }
12984
12985   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12986                      VecIns.back(), VecIns.back());
12987 }
12988
12989 /// \brief return true if \c Op has a use that doesn't just read flags.
12990 static bool hasNonFlagsUse(SDValue Op) {
12991   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12992        ++UI) {
12993     SDNode *User = *UI;
12994     unsigned UOpNo = UI.getOperandNo();
12995     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12996       // Look pass truncate.
12997       UOpNo = User->use_begin().getOperandNo();
12998       User = *User->use_begin();
12999     }
13000
13001     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13002         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13003       return true;
13004   }
13005   return false;
13006 }
13007
13008 /// Emit nodes that will be selected as "test Op0,Op0", or something
13009 /// equivalent.
13010 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13011                                     SelectionDAG &DAG) const {
13012   if (Op.getValueType() == MVT::i1) {
13013     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13014     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13015                        DAG.getConstant(0, dl, MVT::i8));
13016   }
13017   // CF and OF aren't always set the way we want. Determine which
13018   // of these we need.
13019   bool NeedCF = false;
13020   bool NeedOF = false;
13021   switch (X86CC) {
13022   default: break;
13023   case X86::COND_A: case X86::COND_AE:
13024   case X86::COND_B: case X86::COND_BE:
13025     NeedCF = true;
13026     break;
13027   case X86::COND_G: case X86::COND_GE:
13028   case X86::COND_L: case X86::COND_LE:
13029   case X86::COND_O: case X86::COND_NO: {
13030     // Check if we really need to set the
13031     // Overflow flag. If NoSignedWrap is present
13032     // that is not actually needed.
13033     switch (Op->getOpcode()) {
13034     case ISD::ADD:
13035     case ISD::SUB:
13036     case ISD::MUL:
13037     case ISD::SHL: {
13038       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13039       if (BinNode->Flags.hasNoSignedWrap())
13040         break;
13041     }
13042     default:
13043       NeedOF = true;
13044       break;
13045     }
13046     break;
13047   }
13048   }
13049   // See if we can use the EFLAGS value from the operand instead of
13050   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13051   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13052   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13053     // Emit a CMP with 0, which is the TEST pattern.
13054     //if (Op.getValueType() == MVT::i1)
13055     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13056     //                     DAG.getConstant(0, MVT::i1));
13057     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13058                        DAG.getConstant(0, dl, Op.getValueType()));
13059   }
13060   unsigned Opcode = 0;
13061   unsigned NumOperands = 0;
13062
13063   // Truncate operations may prevent the merge of the SETCC instruction
13064   // and the arithmetic instruction before it. Attempt to truncate the operands
13065   // of the arithmetic instruction and use a reduced bit-width instruction.
13066   bool NeedTruncation = false;
13067   SDValue ArithOp = Op;
13068   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13069     SDValue Arith = Op->getOperand(0);
13070     // Both the trunc and the arithmetic op need to have one user each.
13071     if (Arith->hasOneUse())
13072       switch (Arith.getOpcode()) {
13073         default: break;
13074         case ISD::ADD:
13075         case ISD::SUB:
13076         case ISD::AND:
13077         case ISD::OR:
13078         case ISD::XOR: {
13079           NeedTruncation = true;
13080           ArithOp = Arith;
13081         }
13082       }
13083   }
13084
13085   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13086   // which may be the result of a CAST.  We use the variable 'Op', which is the
13087   // non-casted variable when we check for possible users.
13088   switch (ArithOp.getOpcode()) {
13089   case ISD::ADD:
13090     // Due to an isel shortcoming, be conservative if this add is likely to be
13091     // selected as part of a load-modify-store instruction. When the root node
13092     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13093     // uses of other nodes in the match, such as the ADD in this case. This
13094     // leads to the ADD being left around and reselected, with the result being
13095     // two adds in the output.  Alas, even if none our users are stores, that
13096     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13097     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13098     // climbing the DAG back to the root, and it doesn't seem to be worth the
13099     // effort.
13100     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13101          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13102       if (UI->getOpcode() != ISD::CopyToReg &&
13103           UI->getOpcode() != ISD::SETCC &&
13104           UI->getOpcode() != ISD::STORE)
13105         goto default_case;
13106
13107     if (ConstantSDNode *C =
13108         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13109       // An add of one will be selected as an INC.
13110       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13111         Opcode = X86ISD::INC;
13112         NumOperands = 1;
13113         break;
13114       }
13115
13116       // An add of negative one (subtract of one) will be selected as a DEC.
13117       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13118         Opcode = X86ISD::DEC;
13119         NumOperands = 1;
13120         break;
13121       }
13122     }
13123
13124     // Otherwise use a regular EFLAGS-setting add.
13125     Opcode = X86ISD::ADD;
13126     NumOperands = 2;
13127     break;
13128   case ISD::SHL:
13129   case ISD::SRL:
13130     // If we have a constant logical shift that's only used in a comparison
13131     // against zero turn it into an equivalent AND. This allows turning it into
13132     // a TEST instruction later.
13133     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13134         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13135       EVT VT = Op.getValueType();
13136       unsigned BitWidth = VT.getSizeInBits();
13137       unsigned ShAmt = Op->getConstantOperandVal(1);
13138       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13139         break;
13140       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13141                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13142                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13143       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13144         break;
13145       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13146                                 DAG.getConstant(Mask, dl, VT));
13147       DAG.ReplaceAllUsesWith(Op, New);
13148       Op = New;
13149     }
13150     break;
13151
13152   case ISD::AND:
13153     // If the primary and result isn't used, don't bother using X86ISD::AND,
13154     // because a TEST instruction will be better.
13155     if (!hasNonFlagsUse(Op))
13156       break;
13157     // FALL THROUGH
13158   case ISD::SUB:
13159   case ISD::OR:
13160   case ISD::XOR:
13161     // Due to the ISEL shortcoming noted above, be conservative if this op is
13162     // likely to be selected as part of a load-modify-store instruction.
13163     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13164            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13165       if (UI->getOpcode() == ISD::STORE)
13166         goto default_case;
13167
13168     // Otherwise use a regular EFLAGS-setting instruction.
13169     switch (ArithOp.getOpcode()) {
13170     default: llvm_unreachable("unexpected operator!");
13171     case ISD::SUB: Opcode = X86ISD::SUB; break;
13172     case ISD::XOR: Opcode = X86ISD::XOR; break;
13173     case ISD::AND: Opcode = X86ISD::AND; break;
13174     case ISD::OR: {
13175       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13176         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13177         if (EFLAGS.getNode())
13178           return EFLAGS;
13179       }
13180       Opcode = X86ISD::OR;
13181       break;
13182     }
13183     }
13184
13185     NumOperands = 2;
13186     break;
13187   case X86ISD::ADD:
13188   case X86ISD::SUB:
13189   case X86ISD::INC:
13190   case X86ISD::DEC:
13191   case X86ISD::OR:
13192   case X86ISD::XOR:
13193   case X86ISD::AND:
13194     return SDValue(Op.getNode(), 1);
13195   default:
13196   default_case:
13197     break;
13198   }
13199
13200   // If we found that truncation is beneficial, perform the truncation and
13201   // update 'Op'.
13202   if (NeedTruncation) {
13203     EVT VT = Op.getValueType();
13204     SDValue WideVal = Op->getOperand(0);
13205     EVT WideVT = WideVal.getValueType();
13206     unsigned ConvertedOp = 0;
13207     // Use a target machine opcode to prevent further DAGCombine
13208     // optimizations that may separate the arithmetic operations
13209     // from the setcc node.
13210     switch (WideVal.getOpcode()) {
13211       default: break;
13212       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13213       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13214       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13215       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13216       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13217     }
13218
13219     if (ConvertedOp) {
13220       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13221       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13222         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13223         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13224         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13225       }
13226     }
13227   }
13228
13229   if (Opcode == 0)
13230     // Emit a CMP with 0, which is the TEST pattern.
13231     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13232                        DAG.getConstant(0, dl, Op.getValueType()));
13233
13234   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13235   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13236
13237   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13238   DAG.ReplaceAllUsesWith(Op, New);
13239   return SDValue(New.getNode(), 1);
13240 }
13241
13242 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13243 /// equivalent.
13244 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13245                                    SDLoc dl, SelectionDAG &DAG) const {
13246   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13247     if (C->getAPIntValue() == 0)
13248       return EmitTest(Op0, X86CC, dl, DAG);
13249
13250      if (Op0.getValueType() == MVT::i1)
13251        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13252   }
13253
13254   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13255        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13256     // Do the comparison at i32 if it's smaller, besides the Atom case.
13257     // This avoids subregister aliasing issues. Keep the smaller reference
13258     // if we're optimizing for size, however, as that'll allow better folding
13259     // of memory operations.
13260     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13261         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13262         !Subtarget->isAtom()) {
13263       unsigned ExtendOp =
13264           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13265       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13266       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13267     }
13268     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13269     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13270     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13271                               Op0, Op1);
13272     return SDValue(Sub.getNode(), 1);
13273   }
13274   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13275 }
13276
13277 /// Convert a comparison if required by the subtarget.
13278 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13279                                                  SelectionDAG &DAG) const {
13280   // If the subtarget does not support the FUCOMI instruction, floating-point
13281   // comparisons have to be converted.
13282   if (Subtarget->hasCMov() ||
13283       Cmp.getOpcode() != X86ISD::CMP ||
13284       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13285       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13286     return Cmp;
13287
13288   // The instruction selector will select an FUCOM instruction instead of
13289   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13290   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13291   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13292   SDLoc dl(Cmp);
13293   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13294   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13295   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13296                             DAG.getConstant(8, dl, MVT::i8));
13297   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13298   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13299 }
13300
13301 /// The minimum architected relative accuracy is 2^-12. We need one
13302 /// Newton-Raphson step to have a good float result (24 bits of precision).
13303 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13304                                             DAGCombinerInfo &DCI,
13305                                             unsigned &RefinementSteps,
13306                                             bool &UseOneConstNR) const {
13307   EVT VT = Op.getValueType();
13308   const char *RecipOp;
13309
13310   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13311   // TODO: Add support for AVX512 (v16f32).
13312   // It is likely not profitable to do this for f64 because a double-precision
13313   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13314   // instructions: convert to single, rsqrtss, convert back to double, refine
13315   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13316   // along with FMA, this could be a throughput win.
13317   if (VT == MVT::f32 && Subtarget->hasSSE1())
13318     RecipOp = "sqrtf";
13319   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13320            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13321     RecipOp = "vec-sqrtf";
13322   else
13323     return SDValue();
13324
13325   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13326   if (!Recips.isEnabled(RecipOp))
13327     return SDValue();
13328
13329   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13330   UseOneConstNR = false;
13331   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13332 }
13333
13334 /// The minimum architected relative accuracy is 2^-12. We need one
13335 /// Newton-Raphson step to have a good float result (24 bits of precision).
13336 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13337                                             DAGCombinerInfo &DCI,
13338                                             unsigned &RefinementSteps) const {
13339   EVT VT = Op.getValueType();
13340   const char *RecipOp;
13341
13342   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13343   // TODO: Add support for AVX512 (v16f32).
13344   // It is likely not profitable to do this for f64 because a double-precision
13345   // reciprocal estimate with refinement on x86 prior to FMA requires
13346   // 15 instructions: convert to single, rcpss, convert back to double, refine
13347   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13348   // along with FMA, this could be a throughput win.
13349   if (VT == MVT::f32 && Subtarget->hasSSE1())
13350     RecipOp = "divf";
13351   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13352            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13353     RecipOp = "vec-divf";
13354   else
13355     return SDValue();
13356
13357   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13358   if (!Recips.isEnabled(RecipOp))
13359     return SDValue();
13360
13361   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13362   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13363 }
13364
13365 /// If we have at least two divisions that use the same divisor, convert to
13366 /// multplication by a reciprocal. This may need to be adjusted for a given
13367 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13368 /// This is because we still need one division to calculate the reciprocal and
13369 /// then we need two multiplies by that reciprocal as replacements for the
13370 /// original divisions.
13371 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13372   return 2;
13373 }
13374
13375 static bool isAllOnes(SDValue V) {
13376   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13377   return C && C->isAllOnesValue();
13378 }
13379
13380 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13381 /// if it's possible.
13382 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13383                                      SDLoc dl, SelectionDAG &DAG) const {
13384   SDValue Op0 = And.getOperand(0);
13385   SDValue Op1 = And.getOperand(1);
13386   if (Op0.getOpcode() == ISD::TRUNCATE)
13387     Op0 = Op0.getOperand(0);
13388   if (Op1.getOpcode() == ISD::TRUNCATE)
13389     Op1 = Op1.getOperand(0);
13390
13391   SDValue LHS, RHS;
13392   if (Op1.getOpcode() == ISD::SHL)
13393     std::swap(Op0, Op1);
13394   if (Op0.getOpcode() == ISD::SHL) {
13395     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13396       if (And00C->getZExtValue() == 1) {
13397         // If we looked past a truncate, check that it's only truncating away
13398         // known zeros.
13399         unsigned BitWidth = Op0.getValueSizeInBits();
13400         unsigned AndBitWidth = And.getValueSizeInBits();
13401         if (BitWidth > AndBitWidth) {
13402           APInt Zeros, Ones;
13403           DAG.computeKnownBits(Op0, Zeros, Ones);
13404           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13405             return SDValue();
13406         }
13407         LHS = Op1;
13408         RHS = Op0.getOperand(1);
13409       }
13410   } else if (Op1.getOpcode() == ISD::Constant) {
13411     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13412     uint64_t AndRHSVal = AndRHS->getZExtValue();
13413     SDValue AndLHS = Op0;
13414
13415     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13416       LHS = AndLHS.getOperand(0);
13417       RHS = AndLHS.getOperand(1);
13418     }
13419
13420     // Use BT if the immediate can't be encoded in a TEST instruction.
13421     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13422       LHS = AndLHS;
13423       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13424     }
13425   }
13426
13427   if (LHS.getNode()) {
13428     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13429     // instruction.  Since the shift amount is in-range-or-undefined, we know
13430     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13431     // the encoding for the i16 version is larger than the i32 version.
13432     // Also promote i16 to i32 for performance / code size reason.
13433     if (LHS.getValueType() == MVT::i8 ||
13434         LHS.getValueType() == MVT::i16)
13435       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13436
13437     // If the operand types disagree, extend the shift amount to match.  Since
13438     // BT ignores high bits (like shifts) we can use anyextend.
13439     if (LHS.getValueType() != RHS.getValueType())
13440       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13441
13442     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13443     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13444     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13445                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13446   }
13447
13448   return SDValue();
13449 }
13450
13451 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13452 /// mask CMPs.
13453 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13454                               SDValue &Op1) {
13455   unsigned SSECC;
13456   bool Swap = false;
13457
13458   // SSE Condition code mapping:
13459   //  0 - EQ
13460   //  1 - LT
13461   //  2 - LE
13462   //  3 - UNORD
13463   //  4 - NEQ
13464   //  5 - NLT
13465   //  6 - NLE
13466   //  7 - ORD
13467   switch (SetCCOpcode) {
13468   default: llvm_unreachable("Unexpected SETCC condition");
13469   case ISD::SETOEQ:
13470   case ISD::SETEQ:  SSECC = 0; break;
13471   case ISD::SETOGT:
13472   case ISD::SETGT:  Swap = true; // Fallthrough
13473   case ISD::SETLT:
13474   case ISD::SETOLT: SSECC = 1; break;
13475   case ISD::SETOGE:
13476   case ISD::SETGE:  Swap = true; // Fallthrough
13477   case ISD::SETLE:
13478   case ISD::SETOLE: SSECC = 2; break;
13479   case ISD::SETUO:  SSECC = 3; break;
13480   case ISD::SETUNE:
13481   case ISD::SETNE:  SSECC = 4; break;
13482   case ISD::SETULE: Swap = true; // Fallthrough
13483   case ISD::SETUGE: SSECC = 5; break;
13484   case ISD::SETULT: Swap = true; // Fallthrough
13485   case ISD::SETUGT: SSECC = 6; break;
13486   case ISD::SETO:   SSECC = 7; break;
13487   case ISD::SETUEQ:
13488   case ISD::SETONE: SSECC = 8; break;
13489   }
13490   if (Swap)
13491     std::swap(Op0, Op1);
13492
13493   return SSECC;
13494 }
13495
13496 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13497 // ones, and then concatenate the result back.
13498 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13499   MVT VT = Op.getSimpleValueType();
13500
13501   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13502          "Unsupported value type for operation");
13503
13504   unsigned NumElems = VT.getVectorNumElements();
13505   SDLoc dl(Op);
13506   SDValue CC = Op.getOperand(2);
13507
13508   // Extract the LHS vectors
13509   SDValue LHS = Op.getOperand(0);
13510   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13511   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13512
13513   // Extract the RHS vectors
13514   SDValue RHS = Op.getOperand(1);
13515   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13516   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13517
13518   // Issue the operation on the smaller types and concatenate the result back
13519   MVT EltVT = VT.getVectorElementType();
13520   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13521   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13522                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13523                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13524 }
13525
13526 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13527   SDValue Op0 = Op.getOperand(0);
13528   SDValue Op1 = Op.getOperand(1);
13529   SDValue CC = Op.getOperand(2);
13530   MVT VT = Op.getSimpleValueType();
13531   SDLoc dl(Op);
13532
13533   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13534          "Unexpected type for boolean compare operation");
13535   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13536   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13537                                DAG.getConstant(-1, dl, VT));
13538   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13539                                DAG.getConstant(-1, dl, VT));
13540   switch (SetCCOpcode) {
13541   default: llvm_unreachable("Unexpected SETCC condition");
13542   case ISD::SETEQ:
13543     // (x == y) -> ~(x ^ y)
13544     return DAG.getNode(ISD::XOR, dl, VT,
13545                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13546                        DAG.getConstant(-1, dl, VT));
13547   case ISD::SETNE:
13548     // (x != y) -> (x ^ y)
13549     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13550   case ISD::SETUGT:
13551   case ISD::SETGT:
13552     // (x > y) -> (x & ~y)
13553     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13554   case ISD::SETULT:
13555   case ISD::SETLT:
13556     // (x < y) -> (~x & y)
13557     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13558   case ISD::SETULE:
13559   case ISD::SETLE:
13560     // (x <= y) -> (~x | y)
13561     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13562   case ISD::SETUGE:
13563   case ISD::SETGE:
13564     // (x >=y) -> (x | ~y)
13565     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13566   }
13567 }
13568
13569 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13570                                      const X86Subtarget *Subtarget) {
13571   SDValue Op0 = Op.getOperand(0);
13572   SDValue Op1 = Op.getOperand(1);
13573   SDValue CC = Op.getOperand(2);
13574   MVT VT = Op.getSimpleValueType();
13575   SDLoc dl(Op);
13576
13577   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13578          Op.getValueType().getScalarType() == MVT::i1 &&
13579          "Cannot set masked compare for this operation");
13580
13581   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13582   unsigned  Opc = 0;
13583   bool Unsigned = false;
13584   bool Swap = false;
13585   unsigned SSECC;
13586   switch (SetCCOpcode) {
13587   default: llvm_unreachable("Unexpected SETCC condition");
13588   case ISD::SETNE:  SSECC = 4; break;
13589   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13590   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13591   case ISD::SETLT:  Swap = true; //fall-through
13592   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13593   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13594   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13595   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13596   case ISD::SETULE: Unsigned = true; //fall-through
13597   case ISD::SETLE:  SSECC = 2; break;
13598   }
13599
13600   if (Swap)
13601     std::swap(Op0, Op1);
13602   if (Opc)
13603     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13604   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13605   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13606                      DAG.getConstant(SSECC, dl, MVT::i8));
13607 }
13608
13609 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13610 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13611 /// return an empty value.
13612 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13613 {
13614   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13615   if (!BV)
13616     return SDValue();
13617
13618   MVT VT = Op1.getSimpleValueType();
13619   MVT EVT = VT.getVectorElementType();
13620   unsigned n = VT.getVectorNumElements();
13621   SmallVector<SDValue, 8> ULTOp1;
13622
13623   for (unsigned i = 0; i < n; ++i) {
13624     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13625     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13626       return SDValue();
13627
13628     // Avoid underflow.
13629     APInt Val = Elt->getAPIntValue();
13630     if (Val == 0)
13631       return SDValue();
13632
13633     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13634   }
13635
13636   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13637 }
13638
13639 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13640                            SelectionDAG &DAG) {
13641   SDValue Op0 = Op.getOperand(0);
13642   SDValue Op1 = Op.getOperand(1);
13643   SDValue CC = Op.getOperand(2);
13644   MVT VT = Op.getSimpleValueType();
13645   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13646   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13647   SDLoc dl(Op);
13648
13649   if (isFP) {
13650 #ifndef NDEBUG
13651     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13652     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13653 #endif
13654
13655     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13656     unsigned Opc = X86ISD::CMPP;
13657     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13658       assert(VT.getVectorNumElements() <= 16);
13659       Opc = X86ISD::CMPM;
13660     }
13661     // In the two special cases we can't handle, emit two comparisons.
13662     if (SSECC == 8) {
13663       unsigned CC0, CC1;
13664       unsigned CombineOpc;
13665       if (SetCCOpcode == ISD::SETUEQ) {
13666         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13667       } else {
13668         assert(SetCCOpcode == ISD::SETONE);
13669         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13670       }
13671
13672       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13673                                  DAG.getConstant(CC0, dl, MVT::i8));
13674       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13675                                  DAG.getConstant(CC1, dl, MVT::i8));
13676       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13677     }
13678     // Handle all other FP comparisons here.
13679     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13680                        DAG.getConstant(SSECC, dl, MVT::i8));
13681   }
13682
13683   // Break 256-bit integer vector compare into smaller ones.
13684   if (VT.is256BitVector() && !Subtarget->hasInt256())
13685     return Lower256IntVSETCC(Op, DAG);
13686
13687   EVT OpVT = Op1.getValueType();
13688   if (OpVT.getVectorElementType() == MVT::i1)
13689     return LowerBoolVSETCC_AVX512(Op, DAG);
13690
13691   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13692   if (Subtarget->hasAVX512()) {
13693     if (Op1.getValueType().is512BitVector() ||
13694         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13695         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13696       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13697
13698     // In AVX-512 architecture setcc returns mask with i1 elements,
13699     // But there is no compare instruction for i8 and i16 elements in KNL.
13700     // We are not talking about 512-bit operands in this case, these
13701     // types are illegal.
13702     if (MaskResult &&
13703         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13704          OpVT.getVectorElementType().getSizeInBits() >= 8))
13705       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13706                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13707   }
13708
13709   // We are handling one of the integer comparisons here.  Since SSE only has
13710   // GT and EQ comparisons for integer, swapping operands and multiple
13711   // operations may be required for some comparisons.
13712   unsigned Opc;
13713   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13714   bool Subus = false;
13715
13716   switch (SetCCOpcode) {
13717   default: llvm_unreachable("Unexpected SETCC condition");
13718   case ISD::SETNE:  Invert = true;
13719   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13720   case ISD::SETLT:  Swap = true;
13721   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13722   case ISD::SETGE:  Swap = true;
13723   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13724                     Invert = true; break;
13725   case ISD::SETULT: Swap = true;
13726   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13727                     FlipSigns = true; break;
13728   case ISD::SETUGE: Swap = true;
13729   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13730                     FlipSigns = true; Invert = true; break;
13731   }
13732
13733   // Special case: Use min/max operations for SETULE/SETUGE
13734   MVT VET = VT.getVectorElementType();
13735   bool hasMinMax =
13736        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13737     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13738
13739   if (hasMinMax) {
13740     switch (SetCCOpcode) {
13741     default: break;
13742     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13743     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13744     }
13745
13746     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13747   }
13748
13749   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13750   if (!MinMax && hasSubus) {
13751     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13752     // Op0 u<= Op1:
13753     //   t = psubus Op0, Op1
13754     //   pcmpeq t, <0..0>
13755     switch (SetCCOpcode) {
13756     default: break;
13757     case ISD::SETULT: {
13758       // If the comparison is against a constant we can turn this into a
13759       // setule.  With psubus, setule does not require a swap.  This is
13760       // beneficial because the constant in the register is no longer
13761       // destructed as the destination so it can be hoisted out of a loop.
13762       // Only do this pre-AVX since vpcmp* is no longer destructive.
13763       if (Subtarget->hasAVX())
13764         break;
13765       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13766       if (ULEOp1.getNode()) {
13767         Op1 = ULEOp1;
13768         Subus = true; Invert = false; Swap = false;
13769       }
13770       break;
13771     }
13772     // Psubus is better than flip-sign because it requires no inversion.
13773     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13774     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13775     }
13776
13777     if (Subus) {
13778       Opc = X86ISD::SUBUS;
13779       FlipSigns = false;
13780     }
13781   }
13782
13783   if (Swap)
13784     std::swap(Op0, Op1);
13785
13786   // Check that the operation in question is available (most are plain SSE2,
13787   // but PCMPGTQ and PCMPEQQ have different requirements).
13788   if (VT == MVT::v2i64) {
13789     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13790       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13791
13792       // First cast everything to the right type.
13793       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13794       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13795
13796       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13797       // bits of the inputs before performing those operations. The lower
13798       // compare is always unsigned.
13799       SDValue SB;
13800       if (FlipSigns) {
13801         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13802       } else {
13803         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13804         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13805         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13806                          Sign, Zero, Sign, Zero);
13807       }
13808       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13809       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13810
13811       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13812       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13813       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13814
13815       // Create masks for only the low parts/high parts of the 64 bit integers.
13816       static const int MaskHi[] = { 1, 1, 3, 3 };
13817       static const int MaskLo[] = { 0, 0, 2, 2 };
13818       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13819       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13820       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13821
13822       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13823       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13824
13825       if (Invert)
13826         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13827
13828       return DAG.getBitcast(VT, Result);
13829     }
13830
13831     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13832       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13833       // pcmpeqd + pshufd + pand.
13834       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13835
13836       // First cast everything to the right type.
13837       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13838       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13839
13840       // Do the compare.
13841       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13842
13843       // Make sure the lower and upper halves are both all-ones.
13844       static const int Mask[] = { 1, 0, 3, 2 };
13845       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13846       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13847
13848       if (Invert)
13849         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13850
13851       return DAG.getBitcast(VT, Result);
13852     }
13853   }
13854
13855   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13856   // bits of the inputs before performing those operations.
13857   if (FlipSigns) {
13858     EVT EltVT = VT.getVectorElementType();
13859     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13860                                  VT);
13861     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13862     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13863   }
13864
13865   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13866
13867   // If the logical-not of the result is required, perform that now.
13868   if (Invert)
13869     Result = DAG.getNOT(dl, Result, VT);
13870
13871   if (MinMax)
13872     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13873
13874   if (Subus)
13875     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13876                          getZeroVector(VT, Subtarget, DAG, dl));
13877
13878   return Result;
13879 }
13880
13881 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13882
13883   MVT VT = Op.getSimpleValueType();
13884
13885   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13886
13887   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13888          && "SetCC type must be 8-bit or 1-bit integer");
13889   SDValue Op0 = Op.getOperand(0);
13890   SDValue Op1 = Op.getOperand(1);
13891   SDLoc dl(Op);
13892   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13893
13894   // Optimize to BT if possible.
13895   // Lower (X & (1 << N)) == 0 to BT(X, N).
13896   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13897   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13898   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13899       Op1.getOpcode() == ISD::Constant &&
13900       cast<ConstantSDNode>(Op1)->isNullValue() &&
13901       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13902     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13903     if (NewSetCC.getNode()) {
13904       if (VT == MVT::i1)
13905         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13906       return NewSetCC;
13907     }
13908   }
13909
13910   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13911   // these.
13912   if (Op1.getOpcode() == ISD::Constant &&
13913       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13914        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13915       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13916
13917     // If the input is a setcc, then reuse the input setcc or use a new one with
13918     // the inverted condition.
13919     if (Op0.getOpcode() == X86ISD::SETCC) {
13920       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13921       bool Invert = (CC == ISD::SETNE) ^
13922         cast<ConstantSDNode>(Op1)->isNullValue();
13923       if (!Invert)
13924         return Op0;
13925
13926       CCode = X86::GetOppositeBranchCondition(CCode);
13927       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13928                                   DAG.getConstant(CCode, dl, MVT::i8),
13929                                   Op0.getOperand(1));
13930       if (VT == MVT::i1)
13931         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13932       return SetCC;
13933     }
13934   }
13935   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13936       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13937       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13938
13939     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13940     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13941   }
13942
13943   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13944   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13945   if (X86CC == X86::COND_INVALID)
13946     return SDValue();
13947
13948   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13949   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13950   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13951                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13952   if (VT == MVT::i1)
13953     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13954   return SetCC;
13955 }
13956
13957 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13958 static bool isX86LogicalCmp(SDValue Op) {
13959   unsigned Opc = Op.getNode()->getOpcode();
13960   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13961       Opc == X86ISD::SAHF)
13962     return true;
13963   if (Op.getResNo() == 1 &&
13964       (Opc == X86ISD::ADD ||
13965        Opc == X86ISD::SUB ||
13966        Opc == X86ISD::ADC ||
13967        Opc == X86ISD::SBB ||
13968        Opc == X86ISD::SMUL ||
13969        Opc == X86ISD::UMUL ||
13970        Opc == X86ISD::INC ||
13971        Opc == X86ISD::DEC ||
13972        Opc == X86ISD::OR ||
13973        Opc == X86ISD::XOR ||
13974        Opc == X86ISD::AND))
13975     return true;
13976
13977   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13978     return true;
13979
13980   return false;
13981 }
13982
13983 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13984   if (V.getOpcode() != ISD::TRUNCATE)
13985     return false;
13986
13987   SDValue VOp0 = V.getOperand(0);
13988   unsigned InBits = VOp0.getValueSizeInBits();
13989   unsigned Bits = V.getValueSizeInBits();
13990   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13991 }
13992
13993 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13994   bool addTest = true;
13995   SDValue Cond  = Op.getOperand(0);
13996   SDValue Op1 = Op.getOperand(1);
13997   SDValue Op2 = Op.getOperand(2);
13998   SDLoc DL(Op);
13999   EVT VT = Op1.getValueType();
14000   SDValue CC;
14001
14002   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14003   // are available or VBLENDV if AVX is available.
14004   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14005   if (Cond.getOpcode() == ISD::SETCC &&
14006       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14007        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14008       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14009     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14010     int SSECC = translateX86FSETCC(
14011         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14012
14013     if (SSECC != 8) {
14014       if (Subtarget->hasAVX512()) {
14015         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14016                                   DAG.getConstant(SSECC, DL, MVT::i8));
14017         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14018       }
14019
14020       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14021                                 DAG.getConstant(SSECC, DL, MVT::i8));
14022
14023       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14024       // of 3 logic instructions for size savings and potentially speed.
14025       // Unfortunately, there is no scalar form of VBLENDV.
14026
14027       // If either operand is a constant, don't try this. We can expect to
14028       // optimize away at least one of the logic instructions later in that
14029       // case, so that sequence would be faster than a variable blend.
14030
14031       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14032       // uses XMM0 as the selection register. That may need just as many
14033       // instructions as the AND/ANDN/OR sequence due to register moves, so
14034       // don't bother.
14035
14036       if (Subtarget->hasAVX() &&
14037           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14038
14039         // Convert to vectors, do a VSELECT, and convert back to scalar.
14040         // All of the conversions should be optimized away.
14041
14042         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14043         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14044         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14045         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14046
14047         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14048         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14049
14050         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14051
14052         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14053                            VSel, DAG.getIntPtrConstant(0, DL));
14054       }
14055       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14056       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14057       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14058     }
14059   }
14060
14061   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14062     SDValue Op1Scalar;
14063     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14064       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14065     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14066       Op1Scalar = Op1.getOperand(0);
14067     SDValue Op2Scalar;
14068     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14069       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14070     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14071       Op2Scalar = Op2.getOperand(0);
14072     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14073       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14074                                       Op1Scalar.getValueType(),
14075                                       Cond, Op1Scalar, Op2Scalar);
14076       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14077         return DAG.getBitcast(VT, newSelect);
14078       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14079       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14080                          DAG.getIntPtrConstant(0, DL));
14081     }
14082   }
14083
14084   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14085     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14086     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14087                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14088     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14089                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14090     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14091                                     Cond, Op1, Op2);
14092     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14093   }
14094
14095   if (Cond.getOpcode() == ISD::SETCC) {
14096     SDValue NewCond = LowerSETCC(Cond, DAG);
14097     if (NewCond.getNode())
14098       Cond = NewCond;
14099   }
14100
14101   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14102   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14103   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14104   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14105   if (Cond.getOpcode() == X86ISD::SETCC &&
14106       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14107       isZero(Cond.getOperand(1).getOperand(1))) {
14108     SDValue Cmp = Cond.getOperand(1);
14109
14110     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14111
14112     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14113         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14114       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14115
14116       SDValue CmpOp0 = Cmp.getOperand(0);
14117       // Apply further optimizations for special cases
14118       // (select (x != 0), -1, 0) -> neg & sbb
14119       // (select (x == 0), 0, -1) -> neg & sbb
14120       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14121         if (YC->isNullValue() &&
14122             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14123           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14124           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14125                                     DAG.getConstant(0, DL,
14126                                                     CmpOp0.getValueType()),
14127                                     CmpOp0);
14128           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14129                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14130                                     SDValue(Neg.getNode(), 1));
14131           return Res;
14132         }
14133
14134       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14135                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14136       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14137
14138       SDValue Res =   // Res = 0 or -1.
14139         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14140                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14141
14142       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14143         Res = DAG.getNOT(DL, Res, Res.getValueType());
14144
14145       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14146       if (!N2C || !N2C->isNullValue())
14147         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14148       return Res;
14149     }
14150   }
14151
14152   // Look past (and (setcc_carry (cmp ...)), 1).
14153   if (Cond.getOpcode() == ISD::AND &&
14154       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14155     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14156     if (C && C->getAPIntValue() == 1)
14157       Cond = Cond.getOperand(0);
14158   }
14159
14160   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14161   // setting operand in place of the X86ISD::SETCC.
14162   unsigned CondOpcode = Cond.getOpcode();
14163   if (CondOpcode == X86ISD::SETCC ||
14164       CondOpcode == X86ISD::SETCC_CARRY) {
14165     CC = Cond.getOperand(0);
14166
14167     SDValue Cmp = Cond.getOperand(1);
14168     unsigned Opc = Cmp.getOpcode();
14169     MVT VT = Op.getSimpleValueType();
14170
14171     bool IllegalFPCMov = false;
14172     if (VT.isFloatingPoint() && !VT.isVector() &&
14173         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14174       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14175
14176     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14177         Opc == X86ISD::BT) { // FIXME
14178       Cond = Cmp;
14179       addTest = false;
14180     }
14181   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14182              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14183              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14184               Cond.getOperand(0).getValueType() != MVT::i8)) {
14185     SDValue LHS = Cond.getOperand(0);
14186     SDValue RHS = Cond.getOperand(1);
14187     unsigned X86Opcode;
14188     unsigned X86Cond;
14189     SDVTList VTs;
14190     switch (CondOpcode) {
14191     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14192     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14193     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14194     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14195     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14196     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14197     default: llvm_unreachable("unexpected overflowing operator");
14198     }
14199     if (CondOpcode == ISD::UMULO)
14200       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14201                           MVT::i32);
14202     else
14203       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14204
14205     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14206
14207     if (CondOpcode == ISD::UMULO)
14208       Cond = X86Op.getValue(2);
14209     else
14210       Cond = X86Op.getValue(1);
14211
14212     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14213     addTest = false;
14214   }
14215
14216   if (addTest) {
14217     // Look past the truncate if the high bits are known zero.
14218     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14219       Cond = Cond.getOperand(0);
14220
14221     // We know the result of AND is compared against zero. Try to match
14222     // it to BT.
14223     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14224       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14225       if (NewSetCC.getNode()) {
14226         CC = NewSetCC.getOperand(0);
14227         Cond = NewSetCC.getOperand(1);
14228         addTest = false;
14229       }
14230     }
14231   }
14232
14233   if (addTest) {
14234     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14235     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14236   }
14237
14238   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14239   // a <  b ?  0 : -1 -> RES = setcc_carry
14240   // a >= b ? -1 :  0 -> RES = setcc_carry
14241   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14242   if (Cond.getOpcode() == X86ISD::SUB) {
14243     Cond = ConvertCmpIfNecessary(Cond, DAG);
14244     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14245
14246     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14247         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14248       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14249                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14250                                 Cond);
14251       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14252         return DAG.getNOT(DL, Res, Res.getValueType());
14253       return Res;
14254     }
14255   }
14256
14257   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14258   // widen the cmov and push the truncate through. This avoids introducing a new
14259   // branch during isel and doesn't add any extensions.
14260   if (Op.getValueType() == MVT::i8 &&
14261       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14262     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14263     if (T1.getValueType() == T2.getValueType() &&
14264         // Blacklist CopyFromReg to avoid partial register stalls.
14265         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14266       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14267       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14268       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14269     }
14270   }
14271
14272   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14273   // condition is true.
14274   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14275   SDValue Ops[] = { Op2, Op1, CC, Cond };
14276   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14277 }
14278
14279 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14280                                        const X86Subtarget *Subtarget,
14281                                        SelectionDAG &DAG) {
14282   MVT VT = Op->getSimpleValueType(0);
14283   SDValue In = Op->getOperand(0);
14284   MVT InVT = In.getSimpleValueType();
14285   MVT VTElt = VT.getVectorElementType();
14286   MVT InVTElt = InVT.getVectorElementType();
14287   SDLoc dl(Op);
14288
14289   // SKX processor
14290   if ((InVTElt == MVT::i1) &&
14291       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14292         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14293
14294        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14295         VTElt.getSizeInBits() <= 16)) ||
14296
14297        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14298         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14299
14300        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14301         VTElt.getSizeInBits() >= 32))))
14302     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14303
14304   unsigned int NumElts = VT.getVectorNumElements();
14305
14306   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14307     return SDValue();
14308
14309   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14310     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14311       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14312     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14313   }
14314
14315   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14316   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14317   SDValue NegOne =
14318    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14319                    ExtVT);
14320   SDValue Zero =
14321    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14322
14323   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14324   if (VT.is512BitVector())
14325     return V;
14326   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14327 }
14328
14329 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14330                                              const X86Subtarget *Subtarget,
14331                                              SelectionDAG &DAG) {
14332   SDValue In = Op->getOperand(0);
14333   MVT VT = Op->getSimpleValueType(0);
14334   MVT InVT = In.getSimpleValueType();
14335   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14336
14337   MVT InSVT = InVT.getScalarType();
14338   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14339
14340   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14341     return SDValue();
14342   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14343     return SDValue();
14344
14345   SDLoc dl(Op);
14346
14347   // SSE41 targets can use the pmovsx* instructions directly.
14348   if (Subtarget->hasSSE41())
14349     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14350
14351   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14352   SDValue Curr = In;
14353   MVT CurrVT = InVT;
14354
14355   // As SRAI is only available on i16/i32 types, we expand only up to i32
14356   // and handle i64 separately.
14357   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14358     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14359     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14360     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14361     Curr = DAG.getBitcast(CurrVT, Curr);
14362   }
14363
14364   SDValue SignExt = Curr;
14365   if (CurrVT != InVT) {
14366     unsigned SignExtShift =
14367         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14368     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14369                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14370   }
14371
14372   if (CurrVT == VT)
14373     return SignExt;
14374
14375   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14376     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14377                                DAG.getConstant(31, dl, MVT::i8));
14378     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14379     return DAG.getBitcast(VT, Ext);
14380   }
14381
14382   return SDValue();
14383 }
14384
14385 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14386                                 SelectionDAG &DAG) {
14387   MVT VT = Op->getSimpleValueType(0);
14388   SDValue In = Op->getOperand(0);
14389   MVT InVT = In.getSimpleValueType();
14390   SDLoc dl(Op);
14391
14392   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14393     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14394
14395   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14396       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14397       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14398     return SDValue();
14399
14400   if (Subtarget->hasInt256())
14401     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14402
14403   // Optimize vectors in AVX mode
14404   // Sign extend  v8i16 to v8i32 and
14405   //              v4i32 to v4i64
14406   //
14407   // Divide input vector into two parts
14408   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14409   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14410   // concat the vectors to original VT
14411
14412   unsigned NumElems = InVT.getVectorNumElements();
14413   SDValue Undef = DAG.getUNDEF(InVT);
14414
14415   SmallVector<int,8> ShufMask1(NumElems, -1);
14416   for (unsigned i = 0; i != NumElems/2; ++i)
14417     ShufMask1[i] = i;
14418
14419   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14420
14421   SmallVector<int,8> ShufMask2(NumElems, -1);
14422   for (unsigned i = 0; i != NumElems/2; ++i)
14423     ShufMask2[i] = i + NumElems/2;
14424
14425   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14426
14427   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14428                                 VT.getVectorNumElements()/2);
14429
14430   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14431   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14432
14433   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14434 }
14435
14436 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14437 // may emit an illegal shuffle but the expansion is still better than scalar
14438 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14439 // we'll emit a shuffle and a arithmetic shift.
14440 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14441 // TODO: It is possible to support ZExt by zeroing the undef values during
14442 // the shuffle phase or after the shuffle.
14443 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14444                                  SelectionDAG &DAG) {
14445   MVT RegVT = Op.getSimpleValueType();
14446   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14447   assert(RegVT.isInteger() &&
14448          "We only custom lower integer vector sext loads.");
14449
14450   // Nothing useful we can do without SSE2 shuffles.
14451   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14452
14453   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14454   SDLoc dl(Ld);
14455   EVT MemVT = Ld->getMemoryVT();
14456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14457   unsigned RegSz = RegVT.getSizeInBits();
14458
14459   ISD::LoadExtType Ext = Ld->getExtensionType();
14460
14461   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14462          && "Only anyext and sext are currently implemented.");
14463   assert(MemVT != RegVT && "Cannot extend to the same type");
14464   assert(MemVT.isVector() && "Must load a vector from memory");
14465
14466   unsigned NumElems = RegVT.getVectorNumElements();
14467   unsigned MemSz = MemVT.getSizeInBits();
14468   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14469
14470   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14471     // The only way in which we have a legal 256-bit vector result but not the
14472     // integer 256-bit operations needed to directly lower a sextload is if we
14473     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14474     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14475     // correctly legalized. We do this late to allow the canonical form of
14476     // sextload to persist throughout the rest of the DAG combiner -- it wants
14477     // to fold together any extensions it can, and so will fuse a sign_extend
14478     // of an sextload into a sextload targeting a wider value.
14479     SDValue Load;
14480     if (MemSz == 128) {
14481       // Just switch this to a normal load.
14482       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14483                                        "it must be a legal 128-bit vector "
14484                                        "type!");
14485       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14486                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14487                   Ld->isInvariant(), Ld->getAlignment());
14488     } else {
14489       assert(MemSz < 128 &&
14490              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14491       // Do an sext load to a 128-bit vector type. We want to use the same
14492       // number of elements, but elements half as wide. This will end up being
14493       // recursively lowered by this routine, but will succeed as we definitely
14494       // have all the necessary features if we're using AVX1.
14495       EVT HalfEltVT =
14496           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14497       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14498       Load =
14499           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14500                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14501                          Ld->isNonTemporal(), Ld->isInvariant(),
14502                          Ld->getAlignment());
14503     }
14504
14505     // Replace chain users with the new chain.
14506     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14507     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14508
14509     // Finally, do a normal sign-extend to the desired register.
14510     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14511   }
14512
14513   // All sizes must be a power of two.
14514   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14515          "Non-power-of-two elements are not custom lowered!");
14516
14517   // Attempt to load the original value using scalar loads.
14518   // Find the largest scalar type that divides the total loaded size.
14519   MVT SclrLoadTy = MVT::i8;
14520   for (MVT Tp : MVT::integer_valuetypes()) {
14521     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14522       SclrLoadTy = Tp;
14523     }
14524   }
14525
14526   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14527   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14528       (64 <= MemSz))
14529     SclrLoadTy = MVT::f64;
14530
14531   // Calculate the number of scalar loads that we need to perform
14532   // in order to load our vector from memory.
14533   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14534
14535   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14536          "Can only lower sext loads with a single scalar load!");
14537
14538   unsigned loadRegZize = RegSz;
14539   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14540     loadRegZize = 128;
14541
14542   // Represent our vector as a sequence of elements which are the
14543   // largest scalar that we can load.
14544   EVT LoadUnitVecVT = EVT::getVectorVT(
14545       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14546
14547   // Represent the data using the same element type that is stored in
14548   // memory. In practice, we ''widen'' MemVT.
14549   EVT WideVecVT =
14550       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14551                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14552
14553   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14554          "Invalid vector type");
14555
14556   // We can't shuffle using an illegal type.
14557   assert(TLI.isTypeLegal(WideVecVT) &&
14558          "We only lower types that form legal widened vector types");
14559
14560   SmallVector<SDValue, 8> Chains;
14561   SDValue Ptr = Ld->getBasePtr();
14562   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14563                                       TLI.getPointerTy(DAG.getDataLayout()));
14564   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14565
14566   for (unsigned i = 0; i < NumLoads; ++i) {
14567     // Perform a single load.
14568     SDValue ScalarLoad =
14569         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14570                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14571                     Ld->getAlignment());
14572     Chains.push_back(ScalarLoad.getValue(1));
14573     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14574     // another round of DAGCombining.
14575     if (i == 0)
14576       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14577     else
14578       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14579                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14580
14581     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14582   }
14583
14584   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14585
14586   // Bitcast the loaded value to a vector of the original element type, in
14587   // the size of the target vector type.
14588   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14589   unsigned SizeRatio = RegSz / MemSz;
14590
14591   if (Ext == ISD::SEXTLOAD) {
14592     // If we have SSE4.1, we can directly emit a VSEXT node.
14593     if (Subtarget->hasSSE41()) {
14594       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14595       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14596       return Sext;
14597     }
14598
14599     // Otherwise we'll shuffle the small elements in the high bits of the
14600     // larger type and perform an arithmetic shift. If the shift is not legal
14601     // it's better to scalarize.
14602     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14603            "We can't implement a sext load without an arithmetic right shift!");
14604
14605     // Redistribute the loaded elements into the different locations.
14606     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14607     for (unsigned i = 0; i != NumElems; ++i)
14608       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14609
14610     SDValue Shuff = DAG.getVectorShuffle(
14611         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14612
14613     Shuff = DAG.getBitcast(RegVT, Shuff);
14614
14615     // Build the arithmetic shift.
14616     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14617                    MemVT.getVectorElementType().getSizeInBits();
14618     Shuff =
14619         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14620                     DAG.getConstant(Amt, dl, RegVT));
14621
14622     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14623     return Shuff;
14624   }
14625
14626   // Redistribute the loaded elements into the different locations.
14627   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14628   for (unsigned i = 0; i != NumElems; ++i)
14629     ShuffleVec[i * SizeRatio] = i;
14630
14631   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14632                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14633
14634   // Bitcast to the requested type.
14635   Shuff = DAG.getBitcast(RegVT, Shuff);
14636   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14637   return Shuff;
14638 }
14639
14640 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14641 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14642 // from the AND / OR.
14643 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14644   Opc = Op.getOpcode();
14645   if (Opc != ISD::OR && Opc != ISD::AND)
14646     return false;
14647   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14648           Op.getOperand(0).hasOneUse() &&
14649           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14650           Op.getOperand(1).hasOneUse());
14651 }
14652
14653 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14654 // 1 and that the SETCC node has a single use.
14655 static bool isXor1OfSetCC(SDValue Op) {
14656   if (Op.getOpcode() != ISD::XOR)
14657     return false;
14658   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14659   if (N1C && N1C->getAPIntValue() == 1) {
14660     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14661       Op.getOperand(0).hasOneUse();
14662   }
14663   return false;
14664 }
14665
14666 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14667   bool addTest = true;
14668   SDValue Chain = Op.getOperand(0);
14669   SDValue Cond  = Op.getOperand(1);
14670   SDValue Dest  = Op.getOperand(2);
14671   SDLoc dl(Op);
14672   SDValue CC;
14673   bool Inverted = false;
14674
14675   if (Cond.getOpcode() == ISD::SETCC) {
14676     // Check for setcc([su]{add,sub,mul}o == 0).
14677     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14678         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14679         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14680         Cond.getOperand(0).getResNo() == 1 &&
14681         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14682          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14683          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14684          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14685          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14686          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14687       Inverted = true;
14688       Cond = Cond.getOperand(0);
14689     } else {
14690       SDValue NewCond = LowerSETCC(Cond, DAG);
14691       if (NewCond.getNode())
14692         Cond = NewCond;
14693     }
14694   }
14695 #if 0
14696   // FIXME: LowerXALUO doesn't handle these!!
14697   else if (Cond.getOpcode() == X86ISD::ADD  ||
14698            Cond.getOpcode() == X86ISD::SUB  ||
14699            Cond.getOpcode() == X86ISD::SMUL ||
14700            Cond.getOpcode() == X86ISD::UMUL)
14701     Cond = LowerXALUO(Cond, DAG);
14702 #endif
14703
14704   // Look pass (and (setcc_carry (cmp ...)), 1).
14705   if (Cond.getOpcode() == ISD::AND &&
14706       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14707     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14708     if (C && C->getAPIntValue() == 1)
14709       Cond = Cond.getOperand(0);
14710   }
14711
14712   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14713   // setting operand in place of the X86ISD::SETCC.
14714   unsigned CondOpcode = Cond.getOpcode();
14715   if (CondOpcode == X86ISD::SETCC ||
14716       CondOpcode == X86ISD::SETCC_CARRY) {
14717     CC = Cond.getOperand(0);
14718
14719     SDValue Cmp = Cond.getOperand(1);
14720     unsigned Opc = Cmp.getOpcode();
14721     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14722     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14723       Cond = Cmp;
14724       addTest = false;
14725     } else {
14726       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14727       default: break;
14728       case X86::COND_O:
14729       case X86::COND_B:
14730         // These can only come from an arithmetic instruction with overflow,
14731         // e.g. SADDO, UADDO.
14732         Cond = Cond.getNode()->getOperand(1);
14733         addTest = false;
14734         break;
14735       }
14736     }
14737   }
14738   CondOpcode = Cond.getOpcode();
14739   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14740       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14741       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14742        Cond.getOperand(0).getValueType() != MVT::i8)) {
14743     SDValue LHS = Cond.getOperand(0);
14744     SDValue RHS = Cond.getOperand(1);
14745     unsigned X86Opcode;
14746     unsigned X86Cond;
14747     SDVTList VTs;
14748     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14749     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14750     // X86ISD::INC).
14751     switch (CondOpcode) {
14752     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14753     case ISD::SADDO:
14754       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14755         if (C->isOne()) {
14756           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14757           break;
14758         }
14759       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14760     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14761     case ISD::SSUBO:
14762       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14763         if (C->isOne()) {
14764           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14765           break;
14766         }
14767       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14768     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14769     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14770     default: llvm_unreachable("unexpected overflowing operator");
14771     }
14772     if (Inverted)
14773       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14774     if (CondOpcode == ISD::UMULO)
14775       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14776                           MVT::i32);
14777     else
14778       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14779
14780     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14781
14782     if (CondOpcode == ISD::UMULO)
14783       Cond = X86Op.getValue(2);
14784     else
14785       Cond = X86Op.getValue(1);
14786
14787     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14788     addTest = false;
14789   } else {
14790     unsigned CondOpc;
14791     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14792       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14793       if (CondOpc == ISD::OR) {
14794         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14795         // two branches instead of an explicit OR instruction with a
14796         // separate test.
14797         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14798             isX86LogicalCmp(Cmp)) {
14799           CC = Cond.getOperand(0).getOperand(0);
14800           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14801                               Chain, Dest, CC, Cmp);
14802           CC = Cond.getOperand(1).getOperand(0);
14803           Cond = Cmp;
14804           addTest = false;
14805         }
14806       } else { // ISD::AND
14807         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14808         // two branches instead of an explicit AND instruction with a
14809         // separate test. However, we only do this if this block doesn't
14810         // have a fall-through edge, because this requires an explicit
14811         // jmp when the condition is false.
14812         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14813             isX86LogicalCmp(Cmp) &&
14814             Op.getNode()->hasOneUse()) {
14815           X86::CondCode CCode =
14816             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14817           CCode = X86::GetOppositeBranchCondition(CCode);
14818           CC = DAG.getConstant(CCode, dl, MVT::i8);
14819           SDNode *User = *Op.getNode()->use_begin();
14820           // Look for an unconditional branch following this conditional branch.
14821           // We need this because we need to reverse the successors in order
14822           // to implement FCMP_OEQ.
14823           if (User->getOpcode() == ISD::BR) {
14824             SDValue FalseBB = User->getOperand(1);
14825             SDNode *NewBR =
14826               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14827             assert(NewBR == User);
14828             (void)NewBR;
14829             Dest = FalseBB;
14830
14831             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14832                                 Chain, Dest, CC, Cmp);
14833             X86::CondCode CCode =
14834               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14835             CCode = X86::GetOppositeBranchCondition(CCode);
14836             CC = DAG.getConstant(CCode, dl, MVT::i8);
14837             Cond = Cmp;
14838             addTest = false;
14839           }
14840         }
14841       }
14842     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14843       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14844       // It should be transformed during dag combiner except when the condition
14845       // is set by a arithmetics with overflow node.
14846       X86::CondCode CCode =
14847         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14848       CCode = X86::GetOppositeBranchCondition(CCode);
14849       CC = DAG.getConstant(CCode, dl, MVT::i8);
14850       Cond = Cond.getOperand(0).getOperand(1);
14851       addTest = false;
14852     } else if (Cond.getOpcode() == ISD::SETCC &&
14853                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14854       // For FCMP_OEQ, we can emit
14855       // two branches instead of an explicit AND instruction with a
14856       // separate test. However, we only do this if this block doesn't
14857       // have a fall-through edge, because this requires an explicit
14858       // jmp when the condition is false.
14859       if (Op.getNode()->hasOneUse()) {
14860         SDNode *User = *Op.getNode()->use_begin();
14861         // Look for an unconditional branch following this conditional branch.
14862         // We need this because we need to reverse the successors in order
14863         // to implement FCMP_OEQ.
14864         if (User->getOpcode() == ISD::BR) {
14865           SDValue FalseBB = User->getOperand(1);
14866           SDNode *NewBR =
14867             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14868           assert(NewBR == User);
14869           (void)NewBR;
14870           Dest = FalseBB;
14871
14872           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14873                                     Cond.getOperand(0), Cond.getOperand(1));
14874           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14875           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14876           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14877                               Chain, Dest, CC, Cmp);
14878           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14879           Cond = Cmp;
14880           addTest = false;
14881         }
14882       }
14883     } else if (Cond.getOpcode() == ISD::SETCC &&
14884                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14885       // For FCMP_UNE, we can emit
14886       // two branches instead of an explicit AND instruction with a
14887       // separate test. However, we only do this if this block doesn't
14888       // have a fall-through edge, because this requires an explicit
14889       // jmp when the condition is false.
14890       if (Op.getNode()->hasOneUse()) {
14891         SDNode *User = *Op.getNode()->use_begin();
14892         // Look for an unconditional branch following this conditional branch.
14893         // We need this because we need to reverse the successors in order
14894         // to implement FCMP_UNE.
14895         if (User->getOpcode() == ISD::BR) {
14896           SDValue FalseBB = User->getOperand(1);
14897           SDNode *NewBR =
14898             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14899           assert(NewBR == User);
14900           (void)NewBR;
14901
14902           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14903                                     Cond.getOperand(0), Cond.getOperand(1));
14904           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14905           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14906           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14907                               Chain, Dest, CC, Cmp);
14908           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14909           Cond = Cmp;
14910           addTest = false;
14911           Dest = FalseBB;
14912         }
14913       }
14914     }
14915   }
14916
14917   if (addTest) {
14918     // Look pass the truncate if the high bits are known zero.
14919     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14920         Cond = Cond.getOperand(0);
14921
14922     // We know the result of AND is compared against zero. Try to match
14923     // it to BT.
14924     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14925       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14926       if (NewSetCC.getNode()) {
14927         CC = NewSetCC.getOperand(0);
14928         Cond = NewSetCC.getOperand(1);
14929         addTest = false;
14930       }
14931     }
14932   }
14933
14934   if (addTest) {
14935     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14936     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14937     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14938   }
14939   Cond = ConvertCmpIfNecessary(Cond, DAG);
14940   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14941                      Chain, Dest, CC, Cond);
14942 }
14943
14944 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14945 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14946 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14947 // that the guard pages used by the OS virtual memory manager are allocated in
14948 // correct sequence.
14949 SDValue
14950 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14951                                            SelectionDAG &DAG) const {
14952   MachineFunction &MF = DAG.getMachineFunction();
14953   bool SplitStack = MF.shouldSplitStack();
14954   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14955                SplitStack;
14956   SDLoc dl(Op);
14957
14958   if (!Lower) {
14959     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14960     SDNode* Node = Op.getNode();
14961
14962     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14963     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14964         " not tell us which reg is the stack pointer!");
14965     EVT VT = Node->getValueType(0);
14966     SDValue Tmp1 = SDValue(Node, 0);
14967     SDValue Tmp2 = SDValue(Node, 1);
14968     SDValue Tmp3 = Node->getOperand(2);
14969     SDValue Chain = Tmp1.getOperand(0);
14970
14971     // Chain the dynamic stack allocation so that it doesn't modify the stack
14972     // pointer when other instructions are using the stack.
14973     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14974         SDLoc(Node));
14975
14976     SDValue Size = Tmp2.getOperand(1);
14977     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14978     Chain = SP.getValue(1);
14979     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14980     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14981     unsigned StackAlign = TFI.getStackAlignment();
14982     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14983     if (Align > StackAlign)
14984       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14985           DAG.getConstant(-(uint64_t)Align, dl, VT));
14986     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14987
14988     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14989         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14990         SDLoc(Node));
14991
14992     SDValue Ops[2] = { Tmp1, Tmp2 };
14993     return DAG.getMergeValues(Ops, dl);
14994   }
14995
14996   // Get the inputs.
14997   SDValue Chain = Op.getOperand(0);
14998   SDValue Size  = Op.getOperand(1);
14999   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15000   EVT VT = Op.getNode()->getValueType(0);
15001
15002   bool Is64Bit = Subtarget->is64Bit();
15003   MVT SPTy = getPointerTy(DAG.getDataLayout());
15004
15005   if (SplitStack) {
15006     MachineRegisterInfo &MRI = MF.getRegInfo();
15007
15008     if (Is64Bit) {
15009       // The 64 bit implementation of segmented stacks needs to clobber both r10
15010       // r11. This makes it impossible to use it along with nested parameters.
15011       const Function *F = MF.getFunction();
15012
15013       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15014            I != E; ++I)
15015         if (I->hasNestAttr())
15016           report_fatal_error("Cannot use segmented stacks with functions that "
15017                              "have nested arguments.");
15018     }
15019
15020     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15021     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15022     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15023     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15024                                 DAG.getRegister(Vreg, SPTy));
15025     SDValue Ops1[2] = { Value, Chain };
15026     return DAG.getMergeValues(Ops1, dl);
15027   } else {
15028     SDValue Flag;
15029     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15030
15031     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15032     Flag = Chain.getValue(1);
15033     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15034
15035     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15036
15037     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15038     unsigned SPReg = RegInfo->getStackRegister();
15039     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15040     Chain = SP.getValue(1);
15041
15042     if (Align) {
15043       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15044                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15045       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15046     }
15047
15048     SDValue Ops1[2] = { SP, Chain };
15049     return DAG.getMergeValues(Ops1, dl);
15050   }
15051 }
15052
15053 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15054   MachineFunction &MF = DAG.getMachineFunction();
15055   auto PtrVT = getPointerTy(MF.getDataLayout());
15056   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15057
15058   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15059   SDLoc DL(Op);
15060
15061   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
15062     // vastart just stores the address of the VarArgsFrameIndex slot into the
15063     // memory location argument.
15064     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15065     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15066                         MachinePointerInfo(SV), false, false, 0);
15067   }
15068
15069   // __va_list_tag:
15070   //   gp_offset         (0 - 6 * 8)
15071   //   fp_offset         (48 - 48 + 8 * 16)
15072   //   overflow_arg_area (point to parameters coming in memory).
15073   //   reg_save_area
15074   SmallVector<SDValue, 8> MemOps;
15075   SDValue FIN = Op.getOperand(1);
15076   // Store gp_offset
15077   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15078                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15079                                                DL, MVT::i32),
15080                                FIN, MachinePointerInfo(SV), false, false, 0);
15081   MemOps.push_back(Store);
15082
15083   // Store fp_offset
15084   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15085   Store = DAG.getStore(Op.getOperand(0), DL,
15086                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15087                                        MVT::i32),
15088                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15089   MemOps.push_back(Store);
15090
15091   // Store ptr to overflow_arg_area
15092   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15093   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15094   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15095                        MachinePointerInfo(SV, 8),
15096                        false, false, 0);
15097   MemOps.push_back(Store);
15098
15099   // Store ptr to reg_save_area.
15100   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15101   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15102   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15103                        MachinePointerInfo(SV, 16), false, false, 0);
15104   MemOps.push_back(Store);
15105   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15106 }
15107
15108 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15109   assert(Subtarget->is64Bit() &&
15110          "LowerVAARG only handles 64-bit va_arg!");
15111   assert((Subtarget->isTargetLinux() ||
15112           Subtarget->isTargetDarwin()) &&
15113           "Unhandled target in LowerVAARG");
15114   assert(Op.getNode()->getNumOperands() == 4);
15115   SDValue Chain = Op.getOperand(0);
15116   SDValue SrcPtr = Op.getOperand(1);
15117   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15118   unsigned Align = Op.getConstantOperandVal(3);
15119   SDLoc dl(Op);
15120
15121   EVT ArgVT = Op.getNode()->getValueType(0);
15122   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15123   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15124   uint8_t ArgMode;
15125
15126   // Decide which area this value should be read from.
15127   // TODO: Implement the AMD64 ABI in its entirety. This simple
15128   // selection mechanism works only for the basic types.
15129   if (ArgVT == MVT::f80) {
15130     llvm_unreachable("va_arg for f80 not yet implemented");
15131   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15132     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15133   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15134     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15135   } else {
15136     llvm_unreachable("Unhandled argument type in LowerVAARG");
15137   }
15138
15139   if (ArgMode == 2) {
15140     // Sanity Check: Make sure using fp_offset makes sense.
15141     assert(!Subtarget->useSoftFloat() &&
15142            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15143                Attribute::NoImplicitFloat)) &&
15144            Subtarget->hasSSE1());
15145   }
15146
15147   // Insert VAARG_64 node into the DAG
15148   // VAARG_64 returns two values: Variable Argument Address, Chain
15149   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15150                        DAG.getConstant(ArgMode, dl, MVT::i8),
15151                        DAG.getConstant(Align, dl, MVT::i32)};
15152   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15153   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15154                                           VTs, InstOps, MVT::i64,
15155                                           MachinePointerInfo(SV),
15156                                           /*Align=*/0,
15157                                           /*Volatile=*/false,
15158                                           /*ReadMem=*/true,
15159                                           /*WriteMem=*/true);
15160   Chain = VAARG.getValue(1);
15161
15162   // Load the next argument and return it
15163   return DAG.getLoad(ArgVT, dl,
15164                      Chain,
15165                      VAARG,
15166                      MachinePointerInfo(),
15167                      false, false, false, 0);
15168 }
15169
15170 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15171                            SelectionDAG &DAG) {
15172   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15173   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15174   SDValue Chain = Op.getOperand(0);
15175   SDValue DstPtr = Op.getOperand(1);
15176   SDValue SrcPtr = Op.getOperand(2);
15177   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15178   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15179   SDLoc DL(Op);
15180
15181   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15182                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15183                        false, false,
15184                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15185 }
15186
15187 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15188 // amount is a constant. Takes immediate version of shift as input.
15189 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15190                                           SDValue SrcOp, uint64_t ShiftAmt,
15191                                           SelectionDAG &DAG) {
15192   MVT ElementType = VT.getVectorElementType();
15193
15194   // Fold this packed shift into its first operand if ShiftAmt is 0.
15195   if (ShiftAmt == 0)
15196     return SrcOp;
15197
15198   // Check for ShiftAmt >= element width
15199   if (ShiftAmt >= ElementType.getSizeInBits()) {
15200     if (Opc == X86ISD::VSRAI)
15201       ShiftAmt = ElementType.getSizeInBits() - 1;
15202     else
15203       return DAG.getConstant(0, dl, VT);
15204   }
15205
15206   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15207          && "Unknown target vector shift-by-constant node");
15208
15209   // Fold this packed vector shift into a build vector if SrcOp is a
15210   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15211   if (VT == SrcOp.getSimpleValueType() &&
15212       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15213     SmallVector<SDValue, 8> Elts;
15214     unsigned NumElts = SrcOp->getNumOperands();
15215     ConstantSDNode *ND;
15216
15217     switch(Opc) {
15218     default: llvm_unreachable(nullptr);
15219     case X86ISD::VSHLI:
15220       for (unsigned i=0; i!=NumElts; ++i) {
15221         SDValue CurrentOp = SrcOp->getOperand(i);
15222         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15223           Elts.push_back(CurrentOp);
15224           continue;
15225         }
15226         ND = cast<ConstantSDNode>(CurrentOp);
15227         const APInt &C = ND->getAPIntValue();
15228         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15229       }
15230       break;
15231     case X86ISD::VSRLI:
15232       for (unsigned i=0; i!=NumElts; ++i) {
15233         SDValue CurrentOp = SrcOp->getOperand(i);
15234         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15235           Elts.push_back(CurrentOp);
15236           continue;
15237         }
15238         ND = cast<ConstantSDNode>(CurrentOp);
15239         const APInt &C = ND->getAPIntValue();
15240         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15241       }
15242       break;
15243     case X86ISD::VSRAI:
15244       for (unsigned i=0; i!=NumElts; ++i) {
15245         SDValue CurrentOp = SrcOp->getOperand(i);
15246         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15247           Elts.push_back(CurrentOp);
15248           continue;
15249         }
15250         ND = cast<ConstantSDNode>(CurrentOp);
15251         const APInt &C = ND->getAPIntValue();
15252         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15253       }
15254       break;
15255     }
15256
15257     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15258   }
15259
15260   return DAG.getNode(Opc, dl, VT, SrcOp,
15261                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15262 }
15263
15264 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15265 // may or may not be a constant. Takes immediate version of shift as input.
15266 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15267                                    SDValue SrcOp, SDValue ShAmt,
15268                                    SelectionDAG &DAG) {
15269   MVT SVT = ShAmt.getSimpleValueType();
15270   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15271
15272   // Catch shift-by-constant.
15273   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15274     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15275                                       CShAmt->getZExtValue(), DAG);
15276
15277   // Change opcode to non-immediate version
15278   switch (Opc) {
15279     default: llvm_unreachable("Unknown target vector shift node");
15280     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15281     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15282     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15283   }
15284
15285   const X86Subtarget &Subtarget =
15286       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15287   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15288       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15289     // Let the shuffle legalizer expand this shift amount node.
15290     SDValue Op0 = ShAmt.getOperand(0);
15291     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15292     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15293   } else {
15294     // Need to build a vector containing shift amount.
15295     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15296     SmallVector<SDValue, 4> ShOps;
15297     ShOps.push_back(ShAmt);
15298     if (SVT == MVT::i32) {
15299       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15300       ShOps.push_back(DAG.getUNDEF(SVT));
15301     }
15302     ShOps.push_back(DAG.getUNDEF(SVT));
15303
15304     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15305     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15306   }
15307
15308   // The return type has to be a 128-bit type with the same element
15309   // type as the input type.
15310   MVT EltVT = VT.getVectorElementType();
15311   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15312
15313   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15314   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15315 }
15316
15317 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15318 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15319 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15320 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15321                                     SDValue PreservedSrc,
15322                                     const X86Subtarget *Subtarget,
15323                                     SelectionDAG &DAG) {
15324     EVT VT = Op.getValueType();
15325     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15326                                   MVT::i1, VT.getVectorNumElements());
15327     SDValue VMask = SDValue();
15328     unsigned OpcodeSelect = ISD::VSELECT;
15329     SDLoc dl(Op);
15330
15331     assert(MaskVT.isSimple() && "invalid mask type");
15332
15333     if (isAllOnes(Mask))
15334       return Op;
15335
15336     if (MaskVT.bitsGT(Mask.getValueType())) {
15337       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15338                                          MaskVT.getSizeInBits());
15339       VMask = DAG.getBitcast(MaskVT,
15340                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15341     } else {
15342       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15343                                        Mask.getValueType().getSizeInBits());
15344       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15345       // are extracted by EXTRACT_SUBVECTOR.
15346       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15347                           DAG.getBitcast(BitcastVT, Mask),
15348                           DAG.getIntPtrConstant(0, dl));
15349     }
15350
15351     switch (Op.getOpcode()) {
15352       default: break;
15353       case X86ISD::PCMPEQM:
15354       case X86ISD::PCMPGTM:
15355       case X86ISD::CMPM:
15356       case X86ISD::CMPMU:
15357         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15358       case X86ISD::VTRUNC:
15359       case X86ISD::VTRUNCS:
15360       case X86ISD::VTRUNCUS:
15361         // We can't use ISD::VSELECT here because it is not always "Legal"
15362         // for the destination type. For example vpmovqb require only AVX512
15363         // and vselect that can operate on byte element type require BWI
15364         OpcodeSelect = X86ISD::SELECT;
15365         break;
15366     }
15367     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15368       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15369     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15370 }
15371
15372 /// \brief Creates an SDNode for a predicated scalar operation.
15373 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15374 /// The mask is coming as MVT::i8 and it should be truncated
15375 /// to MVT::i1 while lowering masking intrinsics.
15376 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15377 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15378 /// for a scalar instruction.
15379 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15380                                     SDValue PreservedSrc,
15381                                     const X86Subtarget *Subtarget,
15382                                     SelectionDAG &DAG) {
15383     if (isAllOnes(Mask))
15384       return Op;
15385
15386     EVT VT = Op.getValueType();
15387     SDLoc dl(Op);
15388     // The mask should be of type MVT::i1
15389     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15390
15391     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15392       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15393     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15394 }
15395
15396 static int getSEHRegistrationNodeSize(const Function *Fn) {
15397   if (!Fn->hasPersonalityFn())
15398     report_fatal_error(
15399         "querying registration node size for function without personality");
15400   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15401   // WinEHStatePass for the full struct definition.
15402   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15403   case EHPersonality::MSVC_X86SEH: return 24;
15404   case EHPersonality::MSVC_CXX: return 16;
15405   default: break;
15406   }
15407   report_fatal_error("can only recover FP for MSVC EH personality functions");
15408 }
15409
15410 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15411 /// function or when returning to a parent frame after catching an exception, we
15412 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15413 /// Here's the math:
15414 ///   RegNodeBase = EntryEBP - RegNodeSize
15415 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15416 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15417 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15418 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15419                                    SDValue EntryEBP) {
15420   MachineFunction &MF = DAG.getMachineFunction();
15421   SDLoc dl;
15422
15423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15424   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15425
15426   // It's possible that the parent function no longer has a personality function
15427   // if the exceptional code was optimized away, in which case we just return
15428   // the incoming EBP.
15429   if (!Fn->hasPersonalityFn())
15430     return EntryEBP;
15431
15432   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15433
15434   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15435   // registration.
15436   MCSymbol *OffsetSym =
15437       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15438           GlobalValue::getRealLinkageName(Fn->getName()));
15439   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15440   SDValue RegNodeFrameOffset =
15441       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15442
15443   // RegNodeBase = EntryEBP - RegNodeSize
15444   // ParentFP = RegNodeBase - RegNodeFrameOffset
15445   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15446                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15447   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15448 }
15449
15450 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15451                                        SelectionDAG &DAG) {
15452   SDLoc dl(Op);
15453   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15454   EVT VT = Op.getValueType();
15455   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15456   if (IntrData) {
15457     switch(IntrData->Type) {
15458     case INTR_TYPE_1OP:
15459       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15460     case INTR_TYPE_2OP:
15461       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15462         Op.getOperand(2));
15463     case INTR_TYPE_3OP:
15464       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15465         Op.getOperand(2), Op.getOperand(3));
15466     case INTR_TYPE_4OP:
15467       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15468         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15469     case INTR_TYPE_1OP_MASK_RM: {
15470       SDValue Src = Op.getOperand(1);
15471       SDValue PassThru = Op.getOperand(2);
15472       SDValue Mask = Op.getOperand(3);
15473       SDValue RoundingMode;
15474       // We allways add rounding mode to the Node.
15475       // If the rounding mode is not specified, we add the
15476       // "current direction" mode.
15477       if (Op.getNumOperands() == 4)
15478         RoundingMode =
15479           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15480       else
15481         RoundingMode = Op.getOperand(4);
15482       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15483       if (IntrWithRoundingModeOpcode != 0)
15484         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15485             X86::STATIC_ROUNDING::CUR_DIRECTION)
15486           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15487                                       dl, Op.getValueType(), Src, RoundingMode),
15488                                       Mask, PassThru, Subtarget, DAG);
15489       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15490                                               RoundingMode),
15491                                   Mask, PassThru, Subtarget, DAG);
15492     }
15493     case INTR_TYPE_1OP_MASK: {
15494       SDValue Src = Op.getOperand(1);
15495       SDValue PassThru = Op.getOperand(2);
15496       SDValue Mask = Op.getOperand(3);
15497       // We add rounding mode to the Node when
15498       //   - RM Opcode is specified and
15499       //   - RM is not "current direction".
15500       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15501       if (IntrWithRoundingModeOpcode != 0) {
15502         SDValue Rnd = Op.getOperand(4);
15503         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15504         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15505           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15506                                       dl, Op.getValueType(),
15507                                       Src, Rnd),
15508                                       Mask, PassThru, Subtarget, DAG);
15509         }
15510       }
15511       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15512                                   Mask, PassThru, Subtarget, DAG);
15513     }
15514     case INTR_TYPE_SCALAR_MASK_RM: {
15515       SDValue Src1 = Op.getOperand(1);
15516       SDValue Src2 = Op.getOperand(2);
15517       SDValue Src0 = Op.getOperand(3);
15518       SDValue Mask = Op.getOperand(4);
15519       // There are 2 kinds of intrinsics in this group:
15520       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15521       // (2) With rounding mode and sae - 7 operands.
15522       if (Op.getNumOperands() == 6) {
15523         SDValue Sae  = Op.getOperand(5);
15524         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15525         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15526                                                 Sae),
15527                                     Mask, Src0, Subtarget, DAG);
15528       }
15529       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15530       SDValue RoundingMode  = Op.getOperand(5);
15531       SDValue Sae  = Op.getOperand(6);
15532       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15533                                               RoundingMode, Sae),
15534                                   Mask, Src0, Subtarget, DAG);
15535     }
15536     case INTR_TYPE_2OP_MASK: {
15537       SDValue Src1 = Op.getOperand(1);
15538       SDValue Src2 = Op.getOperand(2);
15539       SDValue PassThru = Op.getOperand(3);
15540       SDValue Mask = Op.getOperand(4);
15541       // We specify 2 possible opcodes for intrinsics with rounding modes.
15542       // First, we check if the intrinsic may have non-default rounding mode,
15543       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15544       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15545       if (IntrWithRoundingModeOpcode != 0) {
15546         SDValue Rnd = Op.getOperand(5);
15547         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15548         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15549           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15550                                       dl, Op.getValueType(),
15551                                       Src1, Src2, Rnd),
15552                                       Mask, PassThru, Subtarget, DAG);
15553         }
15554       }
15555       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15556                                               Src1,Src2),
15557                                   Mask, PassThru, Subtarget, DAG);
15558     }
15559     case INTR_TYPE_2OP_MASK_RM: {
15560       SDValue Src1 = Op.getOperand(1);
15561       SDValue Src2 = Op.getOperand(2);
15562       SDValue PassThru = Op.getOperand(3);
15563       SDValue Mask = Op.getOperand(4);
15564       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15565       // First, we check if the intrinsic have rounding mode (6 operands),
15566       // if not, we set rounding mode to "current".
15567       SDValue Rnd;
15568       if (Op.getNumOperands() == 6)
15569         Rnd = Op.getOperand(5);
15570       else
15571         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15572       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15573                                               Src1, Src2, Rnd),
15574                                   Mask, PassThru, Subtarget, DAG);
15575     }
15576     case INTR_TYPE_3OP_MASK_RM: {
15577       SDValue Src1 = Op.getOperand(1);
15578       SDValue Src2 = Op.getOperand(2);
15579       SDValue Imm = Op.getOperand(3);
15580       SDValue PassThru = Op.getOperand(4);
15581       SDValue Mask = Op.getOperand(5);
15582       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15583       // First, we check if the intrinsic have rounding mode (7 operands),
15584       // if not, we set rounding mode to "current".
15585       SDValue Rnd;
15586       if (Op.getNumOperands() == 7)
15587         Rnd = Op.getOperand(6);
15588       else
15589         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15590       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15591         Src1, Src2, Imm, Rnd),
15592         Mask, PassThru, Subtarget, DAG);
15593     }
15594     case INTR_TYPE_3OP_MASK: {
15595       SDValue Src1 = Op.getOperand(1);
15596       SDValue Src2 = Op.getOperand(2);
15597       SDValue Src3 = Op.getOperand(3);
15598       SDValue PassThru = Op.getOperand(4);
15599       SDValue Mask = Op.getOperand(5);
15600       // We specify 2 possible opcodes for intrinsics with rounding modes.
15601       // First, we check if the intrinsic may have non-default rounding mode,
15602       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15603       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15604       if (IntrWithRoundingModeOpcode != 0) {
15605         SDValue Rnd = Op.getOperand(6);
15606         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15607         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15608           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15609                                       dl, Op.getValueType(),
15610                                       Src1, Src2, Src3, Rnd),
15611                                       Mask, PassThru, Subtarget, DAG);
15612         }
15613       }
15614       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15615                                               Src1, Src2, Src3),
15616                                   Mask, PassThru, Subtarget, DAG);
15617     }
15618     case VPERM_3OP_MASKZ:
15619     case VPERM_3OP_MASK:
15620     case FMA_OP_MASK3:
15621     case FMA_OP_MASKZ:
15622     case FMA_OP_MASK: {
15623       SDValue Src1 = Op.getOperand(1);
15624       SDValue Src2 = Op.getOperand(2);
15625       SDValue Src3 = Op.getOperand(3);
15626       SDValue Mask = Op.getOperand(4);
15627       EVT VT = Op.getValueType();
15628       SDValue PassThru = SDValue();
15629
15630       // set PassThru element
15631       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15632         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15633       else if (IntrData->Type == FMA_OP_MASK3)
15634         PassThru = Src3;
15635       else
15636         PassThru = Src1;
15637
15638       // We specify 2 possible opcodes for intrinsics with rounding modes.
15639       // First, we check if the intrinsic may have non-default rounding mode,
15640       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15641       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15642       if (IntrWithRoundingModeOpcode != 0) {
15643         SDValue Rnd = Op.getOperand(5);
15644         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15645             X86::STATIC_ROUNDING::CUR_DIRECTION)
15646           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15647                                                   dl, Op.getValueType(),
15648                                                   Src1, Src2, Src3, Rnd),
15649                                       Mask, PassThru, Subtarget, DAG);
15650       }
15651       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15652                                               dl, Op.getValueType(),
15653                                               Src1, Src2, Src3),
15654                                   Mask, PassThru, Subtarget, DAG);
15655     }
15656     case CMP_MASK:
15657     case CMP_MASK_CC: {
15658       // Comparison intrinsics with masks.
15659       // Example of transformation:
15660       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15661       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15662       // (i8 (bitcast
15663       //   (v8i1 (insert_subvector undef,
15664       //           (v2i1 (and (PCMPEQM %a, %b),
15665       //                      (extract_subvector
15666       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15667       EVT VT = Op.getOperand(1).getValueType();
15668       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15669                                     VT.getVectorNumElements());
15670       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15671       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15672                                        Mask.getValueType().getSizeInBits());
15673       SDValue Cmp;
15674       if (IntrData->Type == CMP_MASK_CC) {
15675         SDValue CC = Op.getOperand(3);
15676         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15677         // We specify 2 possible opcodes for intrinsics with rounding modes.
15678         // First, we check if the intrinsic may have non-default rounding mode,
15679         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15680         if (IntrData->Opc1 != 0) {
15681           SDValue Rnd = Op.getOperand(5);
15682           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15683               X86::STATIC_ROUNDING::CUR_DIRECTION)
15684             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15685                               Op.getOperand(2), CC, Rnd);
15686         }
15687         //default rounding mode
15688         if(!Cmp.getNode())
15689             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15690                               Op.getOperand(2), CC);
15691
15692       } else {
15693         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15694         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15695                           Op.getOperand(2));
15696       }
15697       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15698                                              DAG.getTargetConstant(0, dl,
15699                                                                    MaskVT),
15700                                              Subtarget, DAG);
15701       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15702                                 DAG.getUNDEF(BitcastVT), CmpMask,
15703                                 DAG.getIntPtrConstant(0, dl));
15704       return DAG.getBitcast(Op.getValueType(), Res);
15705     }
15706     case COMI: { // Comparison intrinsics
15707       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15708       SDValue LHS = Op.getOperand(1);
15709       SDValue RHS = Op.getOperand(2);
15710       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15711       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15712       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15713       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15714                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15715       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15716     }
15717     case VSHIFT:
15718       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15719                                  Op.getOperand(1), Op.getOperand(2), DAG);
15720     case VSHIFT_MASK:
15721       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15722                                                       Op.getSimpleValueType(),
15723                                                       Op.getOperand(1),
15724                                                       Op.getOperand(2), DAG),
15725                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15726                                   DAG);
15727     case COMPRESS_EXPAND_IN_REG: {
15728       SDValue Mask = Op.getOperand(3);
15729       SDValue DataToCompress = Op.getOperand(1);
15730       SDValue PassThru = Op.getOperand(2);
15731       if (isAllOnes(Mask)) // return data as is
15732         return Op.getOperand(1);
15733
15734       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15735                                               DataToCompress),
15736                                   Mask, PassThru, Subtarget, DAG);
15737     }
15738     case BLEND: {
15739       SDValue Mask = Op.getOperand(3);
15740       EVT VT = Op.getValueType();
15741       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15742                                     VT.getVectorNumElements());
15743       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15744                                        Mask.getValueType().getSizeInBits());
15745       SDLoc dl(Op);
15746       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15747                                   DAG.getBitcast(BitcastVT, Mask),
15748                                   DAG.getIntPtrConstant(0, dl));
15749       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15750                          Op.getOperand(2));
15751     }
15752     default:
15753       break;
15754     }
15755   }
15756
15757   switch (IntNo) {
15758   default: return SDValue();    // Don't custom lower most intrinsics.
15759
15760   case Intrinsic::x86_avx2_permd:
15761   case Intrinsic::x86_avx2_permps:
15762     // Operands intentionally swapped. Mask is last operand to intrinsic,
15763     // but second operand for node/instruction.
15764     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15765                        Op.getOperand(2), Op.getOperand(1));
15766
15767   // ptest and testp intrinsics. The intrinsic these come from are designed to
15768   // return an integer value, not just an instruction so lower it to the ptest
15769   // or testp pattern and a setcc for the result.
15770   case Intrinsic::x86_sse41_ptestz:
15771   case Intrinsic::x86_sse41_ptestc:
15772   case Intrinsic::x86_sse41_ptestnzc:
15773   case Intrinsic::x86_avx_ptestz_256:
15774   case Intrinsic::x86_avx_ptestc_256:
15775   case Intrinsic::x86_avx_ptestnzc_256:
15776   case Intrinsic::x86_avx_vtestz_ps:
15777   case Intrinsic::x86_avx_vtestc_ps:
15778   case Intrinsic::x86_avx_vtestnzc_ps:
15779   case Intrinsic::x86_avx_vtestz_pd:
15780   case Intrinsic::x86_avx_vtestc_pd:
15781   case Intrinsic::x86_avx_vtestnzc_pd:
15782   case Intrinsic::x86_avx_vtestz_ps_256:
15783   case Intrinsic::x86_avx_vtestc_ps_256:
15784   case Intrinsic::x86_avx_vtestnzc_ps_256:
15785   case Intrinsic::x86_avx_vtestz_pd_256:
15786   case Intrinsic::x86_avx_vtestc_pd_256:
15787   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15788     bool IsTestPacked = false;
15789     unsigned X86CC;
15790     switch (IntNo) {
15791     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15792     case Intrinsic::x86_avx_vtestz_ps:
15793     case Intrinsic::x86_avx_vtestz_pd:
15794     case Intrinsic::x86_avx_vtestz_ps_256:
15795     case Intrinsic::x86_avx_vtestz_pd_256:
15796       IsTestPacked = true; // Fallthrough
15797     case Intrinsic::x86_sse41_ptestz:
15798     case Intrinsic::x86_avx_ptestz_256:
15799       // ZF = 1
15800       X86CC = X86::COND_E;
15801       break;
15802     case Intrinsic::x86_avx_vtestc_ps:
15803     case Intrinsic::x86_avx_vtestc_pd:
15804     case Intrinsic::x86_avx_vtestc_ps_256:
15805     case Intrinsic::x86_avx_vtestc_pd_256:
15806       IsTestPacked = true; // Fallthrough
15807     case Intrinsic::x86_sse41_ptestc:
15808     case Intrinsic::x86_avx_ptestc_256:
15809       // CF = 1
15810       X86CC = X86::COND_B;
15811       break;
15812     case Intrinsic::x86_avx_vtestnzc_ps:
15813     case Intrinsic::x86_avx_vtestnzc_pd:
15814     case Intrinsic::x86_avx_vtestnzc_ps_256:
15815     case Intrinsic::x86_avx_vtestnzc_pd_256:
15816       IsTestPacked = true; // Fallthrough
15817     case Intrinsic::x86_sse41_ptestnzc:
15818     case Intrinsic::x86_avx_ptestnzc_256:
15819       // ZF and CF = 0
15820       X86CC = X86::COND_A;
15821       break;
15822     }
15823
15824     SDValue LHS = Op.getOperand(1);
15825     SDValue RHS = Op.getOperand(2);
15826     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15827     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15828     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15829     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15830     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15831   }
15832   case Intrinsic::x86_avx512_kortestz_w:
15833   case Intrinsic::x86_avx512_kortestc_w: {
15834     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15835     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15836     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15837     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15838     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15839     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15840     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15841   }
15842
15843   case Intrinsic::x86_sse42_pcmpistria128:
15844   case Intrinsic::x86_sse42_pcmpestria128:
15845   case Intrinsic::x86_sse42_pcmpistric128:
15846   case Intrinsic::x86_sse42_pcmpestric128:
15847   case Intrinsic::x86_sse42_pcmpistrio128:
15848   case Intrinsic::x86_sse42_pcmpestrio128:
15849   case Intrinsic::x86_sse42_pcmpistris128:
15850   case Intrinsic::x86_sse42_pcmpestris128:
15851   case Intrinsic::x86_sse42_pcmpistriz128:
15852   case Intrinsic::x86_sse42_pcmpestriz128: {
15853     unsigned Opcode;
15854     unsigned X86CC;
15855     switch (IntNo) {
15856     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15857     case Intrinsic::x86_sse42_pcmpistria128:
15858       Opcode = X86ISD::PCMPISTRI;
15859       X86CC = X86::COND_A;
15860       break;
15861     case Intrinsic::x86_sse42_pcmpestria128:
15862       Opcode = X86ISD::PCMPESTRI;
15863       X86CC = X86::COND_A;
15864       break;
15865     case Intrinsic::x86_sse42_pcmpistric128:
15866       Opcode = X86ISD::PCMPISTRI;
15867       X86CC = X86::COND_B;
15868       break;
15869     case Intrinsic::x86_sse42_pcmpestric128:
15870       Opcode = X86ISD::PCMPESTRI;
15871       X86CC = X86::COND_B;
15872       break;
15873     case Intrinsic::x86_sse42_pcmpistrio128:
15874       Opcode = X86ISD::PCMPISTRI;
15875       X86CC = X86::COND_O;
15876       break;
15877     case Intrinsic::x86_sse42_pcmpestrio128:
15878       Opcode = X86ISD::PCMPESTRI;
15879       X86CC = X86::COND_O;
15880       break;
15881     case Intrinsic::x86_sse42_pcmpistris128:
15882       Opcode = X86ISD::PCMPISTRI;
15883       X86CC = X86::COND_S;
15884       break;
15885     case Intrinsic::x86_sse42_pcmpestris128:
15886       Opcode = X86ISD::PCMPESTRI;
15887       X86CC = X86::COND_S;
15888       break;
15889     case Intrinsic::x86_sse42_pcmpistriz128:
15890       Opcode = X86ISD::PCMPISTRI;
15891       X86CC = X86::COND_E;
15892       break;
15893     case Intrinsic::x86_sse42_pcmpestriz128:
15894       Opcode = X86ISD::PCMPESTRI;
15895       X86CC = X86::COND_E;
15896       break;
15897     }
15898     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15899     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15900     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15901     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15902                                 DAG.getConstant(X86CC, dl, MVT::i8),
15903                                 SDValue(PCMP.getNode(), 1));
15904     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15905   }
15906
15907   case Intrinsic::x86_sse42_pcmpistri128:
15908   case Intrinsic::x86_sse42_pcmpestri128: {
15909     unsigned Opcode;
15910     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15911       Opcode = X86ISD::PCMPISTRI;
15912     else
15913       Opcode = X86ISD::PCMPESTRI;
15914
15915     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15916     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15917     return DAG.getNode(Opcode, dl, VTs, NewOps);
15918   }
15919
15920   case Intrinsic::x86_seh_lsda: {
15921     // Compute the symbol for the LSDA. We know it'll get emitted later.
15922     MachineFunction &MF = DAG.getMachineFunction();
15923     SDValue Op1 = Op.getOperand(1);
15924     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15925     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15926         GlobalValue::getRealLinkageName(Fn->getName()));
15927
15928     // Generate a simple absolute symbol reference. This intrinsic is only
15929     // supported on 32-bit Windows, which isn't PIC.
15930     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15931     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15932   }
15933
15934   case Intrinsic::x86_seh_recoverfp: {
15935     SDValue FnOp = Op.getOperand(1);
15936     SDValue IncomingFPOp = Op.getOperand(2);
15937     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15938     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15939     if (!Fn)
15940       report_fatal_error(
15941           "llvm.x86.seh.recoverfp must take a function as the first argument");
15942     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15943   }
15944
15945   case Intrinsic::localaddress: {
15946     // Returns one of the stack, base, or frame pointer registers, depending on
15947     // which is used to reference local variables.
15948     MachineFunction &MF = DAG.getMachineFunction();
15949     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15950     unsigned Reg;
15951     if (RegInfo->hasBasePointer(MF))
15952       Reg = RegInfo->getBaseRegister();
15953     else // This function handles the SP or FP case.
15954       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15955     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15956   }
15957   }
15958 }
15959
15960 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15961                               SDValue Src, SDValue Mask, SDValue Base,
15962                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15963                               const X86Subtarget * Subtarget) {
15964   SDLoc dl(Op);
15965   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15966   if (!C)
15967     llvm_unreachable("Invalid scale type");
15968   unsigned ScaleVal = C->getZExtValue();
15969   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15970     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15971
15972   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15973   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15974                              Index.getSimpleValueType().getVectorNumElements());
15975   SDValue MaskInReg;
15976   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15977   if (MaskC)
15978     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15979   else {
15980     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15981                                      Mask.getValueType().getSizeInBits());
15982
15983     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15984     // are extracted by EXTRACT_SUBVECTOR.
15985     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15986                             DAG.getBitcast(BitcastVT, Mask),
15987                             DAG.getIntPtrConstant(0, dl));
15988   }
15989   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15990   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15991   SDValue Segment = DAG.getRegister(0, MVT::i32);
15992   if (Src.getOpcode() == ISD::UNDEF)
15993     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15994   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15995   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15996   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15997   return DAG.getMergeValues(RetOps, dl);
15998 }
15999
16000 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16001                                SDValue Src, SDValue Mask, SDValue Base,
16002                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16003   SDLoc dl(Op);
16004   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16005   if (!C)
16006     llvm_unreachable("Invalid scale type");
16007   unsigned ScaleVal = C->getZExtValue();
16008   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16009     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16010
16011   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16012   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16013   SDValue Segment = DAG.getRegister(0, MVT::i32);
16014   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16015                              Index.getSimpleValueType().getVectorNumElements());
16016   SDValue MaskInReg;
16017   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16018   if (MaskC)
16019     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16020   else {
16021     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16022                                      Mask.getValueType().getSizeInBits());
16023
16024     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16025     // are extracted by EXTRACT_SUBVECTOR.
16026     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16027                             DAG.getBitcast(BitcastVT, Mask),
16028                             DAG.getIntPtrConstant(0, dl));
16029   }
16030   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16031   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16032   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16033   return SDValue(Res, 1);
16034 }
16035
16036 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16037                                SDValue Mask, SDValue Base, SDValue Index,
16038                                SDValue ScaleOp, SDValue Chain) {
16039   SDLoc dl(Op);
16040   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16041   assert(C && "Invalid scale type");
16042   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16043   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16044   SDValue Segment = DAG.getRegister(0, MVT::i32);
16045   EVT MaskVT =
16046     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16047   SDValue MaskInReg;
16048   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16049   if (MaskC)
16050     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16051   else
16052     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16053   //SDVTList VTs = DAG.getVTList(MVT::Other);
16054   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16055   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16056   return SDValue(Res, 0);
16057 }
16058
16059 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16060 // read performance monitor counters (x86_rdpmc).
16061 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16062                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16063                               SmallVectorImpl<SDValue> &Results) {
16064   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16065   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16066   SDValue LO, HI;
16067
16068   // The ECX register is used to select the index of the performance counter
16069   // to read.
16070   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16071                                    N->getOperand(2));
16072   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16073
16074   // Reads the content of a 64-bit performance counter and returns it in the
16075   // registers EDX:EAX.
16076   if (Subtarget->is64Bit()) {
16077     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16078     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16079                             LO.getValue(2));
16080   } else {
16081     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16082     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16083                             LO.getValue(2));
16084   }
16085   Chain = HI.getValue(1);
16086
16087   if (Subtarget->is64Bit()) {
16088     // The EAX register is loaded with the low-order 32 bits. The EDX register
16089     // is loaded with the supported high-order bits of the counter.
16090     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16091                               DAG.getConstant(32, DL, MVT::i8));
16092     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16093     Results.push_back(Chain);
16094     return;
16095   }
16096
16097   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16098   SDValue Ops[] = { LO, HI };
16099   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16100   Results.push_back(Pair);
16101   Results.push_back(Chain);
16102 }
16103
16104 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16105 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16106 // also used to custom lower READCYCLECOUNTER nodes.
16107 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16108                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16109                               SmallVectorImpl<SDValue> &Results) {
16110   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16111   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16112   SDValue LO, HI;
16113
16114   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16115   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16116   // and the EAX register is loaded with the low-order 32 bits.
16117   if (Subtarget->is64Bit()) {
16118     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16119     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16120                             LO.getValue(2));
16121   } else {
16122     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16123     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16124                             LO.getValue(2));
16125   }
16126   SDValue Chain = HI.getValue(1);
16127
16128   if (Opcode == X86ISD::RDTSCP_DAG) {
16129     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16130
16131     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16132     // the ECX register. Add 'ecx' explicitly to the chain.
16133     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16134                                      HI.getValue(2));
16135     // Explicitly store the content of ECX at the location passed in input
16136     // to the 'rdtscp' intrinsic.
16137     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16138                          MachinePointerInfo(), false, false, 0);
16139   }
16140
16141   if (Subtarget->is64Bit()) {
16142     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16143     // the EAX register is loaded with the low-order 32 bits.
16144     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16145                               DAG.getConstant(32, DL, MVT::i8));
16146     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16147     Results.push_back(Chain);
16148     return;
16149   }
16150
16151   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16152   SDValue Ops[] = { LO, HI };
16153   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16154   Results.push_back(Pair);
16155   Results.push_back(Chain);
16156 }
16157
16158 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16159                                      SelectionDAG &DAG) {
16160   SmallVector<SDValue, 2> Results;
16161   SDLoc DL(Op);
16162   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16163                           Results);
16164   return DAG.getMergeValues(Results, DL);
16165 }
16166
16167 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16168                                     SelectionDAG &DAG) {
16169   MachineFunction &MF = DAG.getMachineFunction();
16170   const Function *Fn = MF.getFunction();
16171   SDLoc dl(Op);
16172   SDValue Chain = Op.getOperand(0);
16173
16174   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16175          "using llvm.x86.seh.restoreframe requires a frame pointer");
16176
16177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16178   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16179
16180   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16181   unsigned FrameReg =
16182       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16183   unsigned SPReg = RegInfo->getStackRegister();
16184   unsigned SlotSize = RegInfo->getSlotSize();
16185
16186   // Get incoming EBP.
16187   SDValue IncomingEBP =
16188       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16189
16190   // SP is saved in the first field of every registration node, so load
16191   // [EBP-RegNodeSize] into SP.
16192   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16193   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16194                                DAG.getConstant(-RegNodeSize, dl, VT));
16195   SDValue NewSP =
16196       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16197                   false, VT.getScalarSizeInBits() / 8);
16198   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16199
16200   if (!RegInfo->needsStackRealignment(MF)) {
16201     // Adjust EBP to point back to the original frame position.
16202     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16203     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16204   } else {
16205     assert(RegInfo->hasBasePointer(MF) &&
16206            "functions with Win32 EH must use frame or base pointer register");
16207
16208     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16209     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16210     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16211
16212     // Reload the spilled EBP value, now that the stack and base pointers are
16213     // set up.
16214     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16215     X86FI->setHasSEHFramePtrSave(true);
16216     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16217     X86FI->setSEHFramePtrSaveIndex(FI);
16218     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16219                                 MachinePointerInfo(), false, false, false,
16220                                 VT.getScalarSizeInBits() / 8);
16221     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16222   }
16223
16224   return Chain;
16225 }
16226
16227 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16228 /// return truncate Store/MaskedStore Node
16229 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16230                                                SelectionDAG &DAG,
16231                                                MVT ElementType) {
16232   SDLoc dl(Op);
16233   SDValue Mask = Op.getOperand(4);
16234   SDValue DataToTruncate = Op.getOperand(3);
16235   SDValue Addr = Op.getOperand(2);
16236   SDValue Chain = Op.getOperand(0);
16237
16238   EVT VT  = DataToTruncate.getValueType();
16239   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16240                              ElementType, VT.getVectorNumElements());
16241
16242   if (isAllOnes(Mask)) // return just a truncate store
16243     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16244                              MachinePointerInfo(), SVT, false, false,
16245                              SVT.getScalarSizeInBits()/8);
16246
16247   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16248                                 MVT::i1, VT.getVectorNumElements());
16249   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16250                                    Mask.getValueType().getSizeInBits());
16251   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16252   // are extracted by EXTRACT_SUBVECTOR.
16253   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16254                               DAG.getBitcast(BitcastVT, Mask),
16255                               DAG.getIntPtrConstant(0, dl));
16256
16257   MachineMemOperand *MMO = DAG.getMachineFunction().
16258     getMachineMemOperand(MachinePointerInfo(),
16259                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16260                          SVT.getScalarSizeInBits()/8);
16261
16262   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16263                             VMask, SVT, MMO, true);
16264 }
16265
16266 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16267                                       SelectionDAG &DAG) {
16268   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16269
16270   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16271   if (!IntrData) {
16272     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16273       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16274     return SDValue();
16275   }
16276
16277   SDLoc dl(Op);
16278   switch(IntrData->Type) {
16279   default:
16280     llvm_unreachable("Unknown Intrinsic Type");
16281     break;
16282   case RDSEED:
16283   case RDRAND: {
16284     // Emit the node with the right value type.
16285     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16286     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16287
16288     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16289     // Otherwise return the value from Rand, which is always 0, casted to i32.
16290     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16291                       DAG.getConstant(1, dl, Op->getValueType(1)),
16292                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16293                       SDValue(Result.getNode(), 1) };
16294     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16295                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16296                                   Ops);
16297
16298     // Return { result, isValid, chain }.
16299     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16300                        SDValue(Result.getNode(), 2));
16301   }
16302   case GATHER: {
16303   //gather(v1, mask, index, base, scale);
16304     SDValue Chain = Op.getOperand(0);
16305     SDValue Src   = Op.getOperand(2);
16306     SDValue Base  = Op.getOperand(3);
16307     SDValue Index = Op.getOperand(4);
16308     SDValue Mask  = Op.getOperand(5);
16309     SDValue Scale = Op.getOperand(6);
16310     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16311                          Chain, Subtarget);
16312   }
16313   case SCATTER: {
16314   //scatter(base, mask, index, v1, scale);
16315     SDValue Chain = Op.getOperand(0);
16316     SDValue Base  = Op.getOperand(2);
16317     SDValue Mask  = Op.getOperand(3);
16318     SDValue Index = Op.getOperand(4);
16319     SDValue Src   = Op.getOperand(5);
16320     SDValue Scale = Op.getOperand(6);
16321     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16322                           Scale, Chain);
16323   }
16324   case PREFETCH: {
16325     SDValue Hint = Op.getOperand(6);
16326     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16327     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16328     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16329     SDValue Chain = Op.getOperand(0);
16330     SDValue Mask  = Op.getOperand(2);
16331     SDValue Index = Op.getOperand(3);
16332     SDValue Base  = Op.getOperand(4);
16333     SDValue Scale = Op.getOperand(5);
16334     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16335   }
16336   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16337   case RDTSC: {
16338     SmallVector<SDValue, 2> Results;
16339     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16340                             Results);
16341     return DAG.getMergeValues(Results, dl);
16342   }
16343   // Read Performance Monitoring Counters.
16344   case RDPMC: {
16345     SmallVector<SDValue, 2> Results;
16346     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16347     return DAG.getMergeValues(Results, dl);
16348   }
16349   // XTEST intrinsics.
16350   case XTEST: {
16351     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16352     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16353     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16354                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16355                                 InTrans);
16356     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16357     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16358                        Ret, SDValue(InTrans.getNode(), 1));
16359   }
16360   // ADC/ADCX/SBB
16361   case ADX: {
16362     SmallVector<SDValue, 2> Results;
16363     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16364     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16365     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16366                                 DAG.getConstant(-1, dl, MVT::i8));
16367     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16368                               Op.getOperand(4), GenCF.getValue(1));
16369     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16370                                  Op.getOperand(5), MachinePointerInfo(),
16371                                  false, false, 0);
16372     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16373                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16374                                 Res.getValue(1));
16375     Results.push_back(SetCC);
16376     Results.push_back(Store);
16377     return DAG.getMergeValues(Results, dl);
16378   }
16379   case COMPRESS_TO_MEM: {
16380     SDLoc dl(Op);
16381     SDValue Mask = Op.getOperand(4);
16382     SDValue DataToCompress = Op.getOperand(3);
16383     SDValue Addr = Op.getOperand(2);
16384     SDValue Chain = Op.getOperand(0);
16385
16386     EVT VT = DataToCompress.getValueType();
16387     if (isAllOnes(Mask)) // return just a store
16388       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16389                           MachinePointerInfo(), false, false,
16390                           VT.getScalarSizeInBits()/8);
16391
16392     SDValue Compressed =
16393       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16394                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16395     return DAG.getStore(Chain, dl, Compressed, Addr,
16396                         MachinePointerInfo(), false, false,
16397                         VT.getScalarSizeInBits()/8);
16398   }
16399   case TRUNCATE_TO_MEM_VI8:
16400     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16401   case TRUNCATE_TO_MEM_VI16:
16402     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16403   case TRUNCATE_TO_MEM_VI32:
16404     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16405   case EXPAND_FROM_MEM: {
16406     SDLoc dl(Op);
16407     SDValue Mask = Op.getOperand(4);
16408     SDValue PassThru = Op.getOperand(3);
16409     SDValue Addr = Op.getOperand(2);
16410     SDValue Chain = Op.getOperand(0);
16411     EVT VT = Op.getValueType();
16412
16413     if (isAllOnes(Mask)) // return just a load
16414       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16415                          false, VT.getScalarSizeInBits()/8);
16416
16417     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16418                                        false, false, false,
16419                                        VT.getScalarSizeInBits()/8);
16420
16421     SDValue Results[] = {
16422       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16423                            Mask, PassThru, Subtarget, DAG), Chain};
16424     return DAG.getMergeValues(Results, dl);
16425   }
16426   }
16427 }
16428
16429 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16430                                            SelectionDAG &DAG) const {
16431   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16432   MFI->setReturnAddressIsTaken(true);
16433
16434   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16435     return SDValue();
16436
16437   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16438   SDLoc dl(Op);
16439   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16440
16441   if (Depth > 0) {
16442     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16443     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16444     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16445     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16446                        DAG.getNode(ISD::ADD, dl, PtrVT,
16447                                    FrameAddr, Offset),
16448                        MachinePointerInfo(), false, false, false, 0);
16449   }
16450
16451   // Just load the return address.
16452   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16453   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16454                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16455 }
16456
16457 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16458   MachineFunction &MF = DAG.getMachineFunction();
16459   MachineFrameInfo *MFI = MF.getFrameInfo();
16460   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16461   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16462   EVT VT = Op.getValueType();
16463
16464   MFI->setFrameAddressIsTaken(true);
16465
16466   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16467     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16468     // is not possible to crawl up the stack without looking at the unwind codes
16469     // simultaneously.
16470     int FrameAddrIndex = FuncInfo->getFAIndex();
16471     if (!FrameAddrIndex) {
16472       // Set up a frame object for the return address.
16473       unsigned SlotSize = RegInfo->getSlotSize();
16474       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16475           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16476       FuncInfo->setFAIndex(FrameAddrIndex);
16477     }
16478     return DAG.getFrameIndex(FrameAddrIndex, VT);
16479   }
16480
16481   unsigned FrameReg =
16482       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16483   SDLoc dl(Op);  // FIXME probably not meaningful
16484   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16485   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16486           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16487          "Invalid Frame Register!");
16488   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16489   while (Depth--)
16490     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16491                             MachinePointerInfo(),
16492                             false, false, false, 0);
16493   return FrameAddr;
16494 }
16495
16496 // FIXME? Maybe this could be a TableGen attribute on some registers and
16497 // this table could be generated automatically from RegInfo.
16498 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16499                                               SelectionDAG &DAG) const {
16500   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16501   const MachineFunction &MF = DAG.getMachineFunction();
16502
16503   unsigned Reg = StringSwitch<unsigned>(RegName)
16504                        .Case("esp", X86::ESP)
16505                        .Case("rsp", X86::RSP)
16506                        .Case("ebp", X86::EBP)
16507                        .Case("rbp", X86::RBP)
16508                        .Default(0);
16509
16510   if (Reg == X86::EBP || Reg == X86::RBP) {
16511     if (!TFI.hasFP(MF))
16512       report_fatal_error("register " + StringRef(RegName) +
16513                          " is allocatable: function has no frame pointer");
16514 #ifndef NDEBUG
16515     else {
16516       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16517       unsigned FrameReg =
16518           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16519       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16520              "Invalid Frame Register!");
16521     }
16522 #endif
16523   }
16524
16525   if (Reg)
16526     return Reg;
16527
16528   report_fatal_error("Invalid register name global variable");
16529 }
16530
16531 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16532                                                      SelectionDAG &DAG) const {
16533   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16534   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16535 }
16536
16537 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16538   SDValue Chain     = Op.getOperand(0);
16539   SDValue Offset    = Op.getOperand(1);
16540   SDValue Handler   = Op.getOperand(2);
16541   SDLoc dl      (Op);
16542
16543   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16544   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16545   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16546   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16547           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16548          "Invalid Frame Register!");
16549   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16550   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16551
16552   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16553                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16554                                                        dl));
16555   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16556   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16557                        false, false, 0);
16558   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16559
16560   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16561                      DAG.getRegister(StoreAddrReg, PtrVT));
16562 }
16563
16564 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16565                                                SelectionDAG &DAG) const {
16566   SDLoc DL(Op);
16567   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16568                      DAG.getVTList(MVT::i32, MVT::Other),
16569                      Op.getOperand(0), Op.getOperand(1));
16570 }
16571
16572 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16573                                                 SelectionDAG &DAG) const {
16574   SDLoc DL(Op);
16575   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16576                      Op.getOperand(0), Op.getOperand(1));
16577 }
16578
16579 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16580   return Op.getOperand(0);
16581 }
16582
16583 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16584                                                 SelectionDAG &DAG) const {
16585   SDValue Root = Op.getOperand(0);
16586   SDValue Trmp = Op.getOperand(1); // trampoline
16587   SDValue FPtr = Op.getOperand(2); // nested function
16588   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16589   SDLoc dl (Op);
16590
16591   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16592   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16593
16594   if (Subtarget->is64Bit()) {
16595     SDValue OutChains[6];
16596
16597     // Large code-model.
16598     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16599     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16600
16601     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16602     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16603
16604     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16605
16606     // Load the pointer to the nested function into R11.
16607     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16608     SDValue Addr = Trmp;
16609     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16610                                 Addr, MachinePointerInfo(TrmpAddr),
16611                                 false, false, 0);
16612
16613     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16614                        DAG.getConstant(2, dl, MVT::i64));
16615     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16616                                 MachinePointerInfo(TrmpAddr, 2),
16617                                 false, false, 2);
16618
16619     // Load the 'nest' parameter value into R10.
16620     // R10 is specified in X86CallingConv.td
16621     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16622     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16623                        DAG.getConstant(10, dl, MVT::i64));
16624     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16625                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16626                                 false, false, 0);
16627
16628     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16629                        DAG.getConstant(12, dl, MVT::i64));
16630     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16631                                 MachinePointerInfo(TrmpAddr, 12),
16632                                 false, false, 2);
16633
16634     // Jump to the nested function.
16635     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16636     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16637                        DAG.getConstant(20, dl, MVT::i64));
16638     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16639                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16640                                 false, false, 0);
16641
16642     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16643     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16644                        DAG.getConstant(22, dl, MVT::i64));
16645     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16646                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16647                                 false, false, 0);
16648
16649     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16650   } else {
16651     const Function *Func =
16652       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16653     CallingConv::ID CC = Func->getCallingConv();
16654     unsigned NestReg;
16655
16656     switch (CC) {
16657     default:
16658       llvm_unreachable("Unsupported calling convention");
16659     case CallingConv::C:
16660     case CallingConv::X86_StdCall: {
16661       // Pass 'nest' parameter in ECX.
16662       // Must be kept in sync with X86CallingConv.td
16663       NestReg = X86::ECX;
16664
16665       // Check that ECX wasn't needed by an 'inreg' parameter.
16666       FunctionType *FTy = Func->getFunctionType();
16667       const AttributeSet &Attrs = Func->getAttributes();
16668
16669       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16670         unsigned InRegCount = 0;
16671         unsigned Idx = 1;
16672
16673         for (FunctionType::param_iterator I = FTy->param_begin(),
16674              E = FTy->param_end(); I != E; ++I, ++Idx)
16675           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16676             auto &DL = DAG.getDataLayout();
16677             // FIXME: should only count parameters that are lowered to integers.
16678             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16679           }
16680
16681         if (InRegCount > 2) {
16682           report_fatal_error("Nest register in use - reduce number of inreg"
16683                              " parameters!");
16684         }
16685       }
16686       break;
16687     }
16688     case CallingConv::X86_FastCall:
16689     case CallingConv::X86_ThisCall:
16690     case CallingConv::Fast:
16691       // Pass 'nest' parameter in EAX.
16692       // Must be kept in sync with X86CallingConv.td
16693       NestReg = X86::EAX;
16694       break;
16695     }
16696
16697     SDValue OutChains[4];
16698     SDValue Addr, Disp;
16699
16700     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16701                        DAG.getConstant(10, dl, MVT::i32));
16702     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16703
16704     // This is storing the opcode for MOV32ri.
16705     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16706     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16707     OutChains[0] = DAG.getStore(Root, dl,
16708                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16709                                 Trmp, MachinePointerInfo(TrmpAddr),
16710                                 false, false, 0);
16711
16712     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16713                        DAG.getConstant(1, dl, MVT::i32));
16714     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16715                                 MachinePointerInfo(TrmpAddr, 1),
16716                                 false, false, 1);
16717
16718     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16719     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16720                        DAG.getConstant(5, dl, MVT::i32));
16721     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16722                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16723                                 false, false, 1);
16724
16725     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16726                        DAG.getConstant(6, dl, MVT::i32));
16727     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16728                                 MachinePointerInfo(TrmpAddr, 6),
16729                                 false, false, 1);
16730
16731     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16732   }
16733 }
16734
16735 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16736                                             SelectionDAG &DAG) const {
16737   /*
16738    The rounding mode is in bits 11:10 of FPSR, and has the following
16739    settings:
16740      00 Round to nearest
16741      01 Round to -inf
16742      10 Round to +inf
16743      11 Round to 0
16744
16745   FLT_ROUNDS, on the other hand, expects the following:
16746     -1 Undefined
16747      0 Round to 0
16748      1 Round to nearest
16749      2 Round to +inf
16750      3 Round to -inf
16751
16752   To perform the conversion, we do:
16753     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16754   */
16755
16756   MachineFunction &MF = DAG.getMachineFunction();
16757   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16758   unsigned StackAlignment = TFI.getStackAlignment();
16759   MVT VT = Op.getSimpleValueType();
16760   SDLoc DL(Op);
16761
16762   // Save FP Control Word to stack slot
16763   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16764   SDValue StackSlot =
16765       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16766
16767   MachineMemOperand *MMO =
16768       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16769                               MachineMemOperand::MOStore, 2, 2);
16770
16771   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16772   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16773                                           DAG.getVTList(MVT::Other),
16774                                           Ops, MVT::i16, MMO);
16775
16776   // Load FP Control Word from stack slot
16777   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16778                             MachinePointerInfo(), false, false, false, 0);
16779
16780   // Transform as necessary
16781   SDValue CWD1 =
16782     DAG.getNode(ISD::SRL, DL, MVT::i16,
16783                 DAG.getNode(ISD::AND, DL, MVT::i16,
16784                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16785                 DAG.getConstant(11, DL, MVT::i8));
16786   SDValue CWD2 =
16787     DAG.getNode(ISD::SRL, DL, MVT::i16,
16788                 DAG.getNode(ISD::AND, DL, MVT::i16,
16789                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16790                 DAG.getConstant(9, DL, MVT::i8));
16791
16792   SDValue RetVal =
16793     DAG.getNode(ISD::AND, DL, MVT::i16,
16794                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16795                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16796                             DAG.getConstant(1, DL, MVT::i16)),
16797                 DAG.getConstant(3, DL, MVT::i16));
16798
16799   return DAG.getNode((VT.getSizeInBits() < 16 ?
16800                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16801 }
16802
16803 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16804   MVT VT = Op.getSimpleValueType();
16805   EVT OpVT = VT;
16806   unsigned NumBits = VT.getSizeInBits();
16807   SDLoc dl(Op);
16808
16809   Op = Op.getOperand(0);
16810   if (VT == MVT::i8) {
16811     // Zero extend to i32 since there is not an i8 bsr.
16812     OpVT = MVT::i32;
16813     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16814   }
16815
16816   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16817   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16818   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16819
16820   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16821   SDValue Ops[] = {
16822     Op,
16823     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16824     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16825     Op.getValue(1)
16826   };
16827   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16828
16829   // Finally xor with NumBits-1.
16830   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16831                    DAG.getConstant(NumBits - 1, dl, OpVT));
16832
16833   if (VT == MVT::i8)
16834     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16835   return Op;
16836 }
16837
16838 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16839   MVT VT = Op.getSimpleValueType();
16840   EVT OpVT = VT;
16841   unsigned NumBits = VT.getSizeInBits();
16842   SDLoc dl(Op);
16843
16844   Op = Op.getOperand(0);
16845   if (VT == MVT::i8) {
16846     // Zero extend to i32 since there is not an i8 bsr.
16847     OpVT = MVT::i32;
16848     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16849   }
16850
16851   // Issue a bsr (scan bits in reverse).
16852   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16853   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16854
16855   // And xor with NumBits-1.
16856   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16857                    DAG.getConstant(NumBits - 1, dl, OpVT));
16858
16859   if (VT == MVT::i8)
16860     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16861   return Op;
16862 }
16863
16864 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16865   MVT VT = Op.getSimpleValueType();
16866   unsigned NumBits = VT.getSizeInBits();
16867   SDLoc dl(Op);
16868   Op = Op.getOperand(0);
16869
16870   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16871   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16872   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16873
16874   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16875   SDValue Ops[] = {
16876     Op,
16877     DAG.getConstant(NumBits, dl, VT),
16878     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16879     Op.getValue(1)
16880   };
16881   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16882 }
16883
16884 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16885 // ones, and then concatenate the result back.
16886 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16887   MVT VT = Op.getSimpleValueType();
16888
16889   assert(VT.is256BitVector() && VT.isInteger() &&
16890          "Unsupported value type for operation");
16891
16892   unsigned NumElems = VT.getVectorNumElements();
16893   SDLoc dl(Op);
16894
16895   // Extract the LHS vectors
16896   SDValue LHS = Op.getOperand(0);
16897   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16898   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16899
16900   // Extract the RHS vectors
16901   SDValue RHS = Op.getOperand(1);
16902   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16903   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16904
16905   MVT EltVT = VT.getVectorElementType();
16906   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16907
16908   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16909                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16910                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16911 }
16912
16913 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16914   if (Op.getValueType() == MVT::i1)
16915     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16916                        Op.getOperand(0), Op.getOperand(1));
16917   assert(Op.getSimpleValueType().is256BitVector() &&
16918          Op.getSimpleValueType().isInteger() &&
16919          "Only handle AVX 256-bit vector integer operation");
16920   return Lower256IntArith(Op, DAG);
16921 }
16922
16923 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16924   if (Op.getValueType() == MVT::i1)
16925     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16926                        Op.getOperand(0), Op.getOperand(1));
16927   assert(Op.getSimpleValueType().is256BitVector() &&
16928          Op.getSimpleValueType().isInteger() &&
16929          "Only handle AVX 256-bit vector integer operation");
16930   return Lower256IntArith(Op, DAG);
16931 }
16932
16933 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
16934   assert(Op.getSimpleValueType().is256BitVector() &&
16935          Op.getSimpleValueType().isInteger() &&
16936          "Only handle AVX 256-bit vector integer operation");
16937   return Lower256IntArith(Op, DAG);
16938 }
16939
16940 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16941                         SelectionDAG &DAG) {
16942   SDLoc dl(Op);
16943   MVT VT = Op.getSimpleValueType();
16944
16945   if (VT == MVT::i1)
16946     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16947
16948   // Decompose 256-bit ops into smaller 128-bit ops.
16949   if (VT.is256BitVector() && !Subtarget->hasInt256())
16950     return Lower256IntArith(Op, DAG);
16951
16952   SDValue A = Op.getOperand(0);
16953   SDValue B = Op.getOperand(1);
16954
16955   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16956   // pairs, multiply and truncate.
16957   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16958     if (Subtarget->hasInt256()) {
16959       if (VT == MVT::v32i8) {
16960         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16961         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16962         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16963         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16964         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16965         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16966         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16967         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16968                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16969                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16970       }
16971
16972       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16973       return DAG.getNode(
16974           ISD::TRUNCATE, dl, VT,
16975           DAG.getNode(ISD::MUL, dl, ExVT,
16976                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16977                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16978     }
16979
16980     assert(VT == MVT::v16i8 &&
16981            "Pre-AVX2 support only supports v16i8 multiplication");
16982     MVT ExVT = MVT::v8i16;
16983
16984     // Extract the lo parts and sign extend to i16
16985     SDValue ALo, BLo;
16986     if (Subtarget->hasSSE41()) {
16987       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16988       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16989     } else {
16990       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16991                               -1, 4, -1, 5, -1, 6, -1, 7};
16992       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16993       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16994       ALo = DAG.getBitcast(ExVT, ALo);
16995       BLo = DAG.getBitcast(ExVT, BLo);
16996       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16997       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16998     }
16999
17000     // Extract the hi parts and sign extend to i16
17001     SDValue AHi, BHi;
17002     if (Subtarget->hasSSE41()) {
17003       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17004                               -1, -1, -1, -1, -1, -1, -1, -1};
17005       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17006       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17007       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17008       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17009     } else {
17010       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17011                               -1, 12, -1, 13, -1, 14, -1, 15};
17012       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17013       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17014       AHi = DAG.getBitcast(ExVT, AHi);
17015       BHi = DAG.getBitcast(ExVT, BHi);
17016       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17017       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17018     }
17019
17020     // Multiply, mask the lower 8bits of the lo/hi results and pack
17021     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17022     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17023     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17024     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17025     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17026   }
17027
17028   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17029   if (VT == MVT::v4i32) {
17030     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17031            "Should not custom lower when pmuldq is available!");
17032
17033     // Extract the odd parts.
17034     static const int UnpackMask[] = { 1, -1, 3, -1 };
17035     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17036     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17037
17038     // Multiply the even parts.
17039     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17040     // Now multiply odd parts.
17041     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17042
17043     Evens = DAG.getBitcast(VT, Evens);
17044     Odds = DAG.getBitcast(VT, Odds);
17045
17046     // Merge the two vectors back together with a shuffle. This expands into 2
17047     // shuffles.
17048     static const int ShufMask[] = { 0, 4, 2, 6 };
17049     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17050   }
17051
17052   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17053          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17054
17055   //  Ahi = psrlqi(a, 32);
17056   //  Bhi = psrlqi(b, 32);
17057   //
17058   //  AloBlo = pmuludq(a, b);
17059   //  AloBhi = pmuludq(a, Bhi);
17060   //  AhiBlo = pmuludq(Ahi, b);
17061
17062   //  AloBhi = psllqi(AloBhi, 32);
17063   //  AhiBlo = psllqi(AhiBlo, 32);
17064   //  return AloBlo + AloBhi + AhiBlo;
17065
17066   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17067   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17068
17069   SDValue AhiBlo = Ahi;
17070   SDValue AloBhi = Bhi;
17071   // Bit cast to 32-bit vectors for MULUDQ
17072   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17073                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17074   A = DAG.getBitcast(MulVT, A);
17075   B = DAG.getBitcast(MulVT, B);
17076   Ahi = DAG.getBitcast(MulVT, Ahi);
17077   Bhi = DAG.getBitcast(MulVT, Bhi);
17078
17079   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17080   // After shifting right const values the result may be all-zero.
17081   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17082     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17083     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17084   }
17085   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17086     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17087     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17088   }
17089
17090   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17091   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17092 }
17093
17094 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17095   assert(Subtarget->isTargetWin64() && "Unexpected target");
17096   EVT VT = Op.getValueType();
17097   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17098          "Unexpected return type for lowering");
17099
17100   RTLIB::Libcall LC;
17101   bool isSigned;
17102   switch (Op->getOpcode()) {
17103   default: llvm_unreachable("Unexpected request for libcall!");
17104   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17105   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17106   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17107   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17108   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17109   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17110   }
17111
17112   SDLoc dl(Op);
17113   SDValue InChain = DAG.getEntryNode();
17114
17115   TargetLowering::ArgListTy Args;
17116   TargetLowering::ArgListEntry Entry;
17117   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17118     EVT ArgVT = Op->getOperand(i).getValueType();
17119     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17120            "Unexpected argument type for lowering");
17121     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17122     Entry.Node = StackPtr;
17123     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17124                            false, false, 16);
17125     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17126     Entry.Ty = PointerType::get(ArgTy,0);
17127     Entry.isSExt = false;
17128     Entry.isZExt = false;
17129     Args.push_back(Entry);
17130   }
17131
17132   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17133                                          getPointerTy(DAG.getDataLayout()));
17134
17135   TargetLowering::CallLoweringInfo CLI(DAG);
17136   CLI.setDebugLoc(dl).setChain(InChain)
17137     .setCallee(getLibcallCallingConv(LC),
17138                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17139                Callee, std::move(Args), 0)
17140     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17141
17142   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17143   return DAG.getBitcast(VT, CallInfo.first);
17144 }
17145
17146 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17147                              SelectionDAG &DAG) {
17148   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17149   EVT VT = Op0.getValueType();
17150   SDLoc dl(Op);
17151
17152   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17153          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17154
17155   // PMULxD operations multiply each even value (starting at 0) of LHS with
17156   // the related value of RHS and produce a widen result.
17157   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17158   // => <2 x i64> <ae|cg>
17159   //
17160   // In other word, to have all the results, we need to perform two PMULxD:
17161   // 1. one with the even values.
17162   // 2. one with the odd values.
17163   // To achieve #2, with need to place the odd values at an even position.
17164   //
17165   // Place the odd value at an even position (basically, shift all values 1
17166   // step to the left):
17167   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17168   // <a|b|c|d> => <b|undef|d|undef>
17169   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17170   // <e|f|g|h> => <f|undef|h|undef>
17171   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17172
17173   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17174   // ints.
17175   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17176   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17177   unsigned Opcode =
17178       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17179   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17180   // => <2 x i64> <ae|cg>
17181   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17182   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17183   // => <2 x i64> <bf|dh>
17184   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17185
17186   // Shuffle it back into the right order.
17187   SDValue Highs, Lows;
17188   if (VT == MVT::v8i32) {
17189     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17190     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17191     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17192     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17193   } else {
17194     const int HighMask[] = {1, 5, 3, 7};
17195     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17196     const int LowMask[] = {0, 4, 2, 6};
17197     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17198   }
17199
17200   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17201   // unsigned multiply.
17202   if (IsSigned && !Subtarget->hasSSE41()) {
17203     SDValue ShAmt = DAG.getConstant(
17204         31, dl,
17205         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17206     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17207                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17208     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17209                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17210
17211     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17212     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17213   }
17214
17215   // The first result of MUL_LOHI is actually the low value, followed by the
17216   // high value.
17217   SDValue Ops[] = {Lows, Highs};
17218   return DAG.getMergeValues(Ops, dl);
17219 }
17220
17221 // Return true if the required (according to Opcode) shift-imm form is natively
17222 // supported by the Subtarget
17223 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17224                                         unsigned Opcode) {
17225   if (VT.getScalarSizeInBits() < 16)
17226     return false;
17227
17228   if (VT.is512BitVector() &&
17229       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17230     return true;
17231
17232   bool LShift = VT.is128BitVector() ||
17233     (VT.is256BitVector() && Subtarget->hasInt256());
17234
17235   bool AShift = LShift && (Subtarget->hasVLX() ||
17236     (VT != MVT::v2i64 && VT != MVT::v4i64));
17237   return (Opcode == ISD::SRA) ? AShift : LShift;
17238 }
17239
17240 // The shift amount is a variable, but it is the same for all vector lanes.
17241 // These instructions are defined together with shift-immediate.
17242 static
17243 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17244                                       unsigned Opcode) {
17245   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17246 }
17247
17248 // Return true if the required (according to Opcode) variable-shift form is
17249 // natively supported by the Subtarget
17250 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17251                                     unsigned Opcode) {
17252
17253   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17254     return false;
17255
17256   // vXi16 supported only on AVX-512, BWI
17257   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17258     return false;
17259
17260   if (VT.is512BitVector() || Subtarget->hasVLX())
17261     return true;
17262
17263   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17264   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17265   return (Opcode == ISD::SRA) ? AShift : LShift;
17266 }
17267
17268 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17269                                          const X86Subtarget *Subtarget) {
17270   MVT VT = Op.getSimpleValueType();
17271   SDLoc dl(Op);
17272   SDValue R = Op.getOperand(0);
17273   SDValue Amt = Op.getOperand(1);
17274
17275   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17276     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17277
17278   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17279     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17280     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17281     SDValue Ex = DAG.getBitcast(ExVT, R);
17282
17283     if (ShiftAmt >= 32) {
17284       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17285       SDValue Upper =
17286           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17287       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17288                                                  ShiftAmt - 32, DAG);
17289       if (VT == MVT::v2i64)
17290         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17291       if (VT == MVT::v4i64)
17292         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17293                                   {9, 1, 11, 3, 13, 5, 15, 7});
17294     } else {
17295       // SRA upper i32, SHL whole i64 and select lower i32.
17296       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17297                                                  ShiftAmt, DAG);
17298       SDValue Lower =
17299           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17300       Lower = DAG.getBitcast(ExVT, Lower);
17301       if (VT == MVT::v2i64)
17302         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17303       if (VT == MVT::v4i64)
17304         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17305                                   {8, 1, 10, 3, 12, 5, 14, 7});
17306     }
17307     return DAG.getBitcast(VT, Ex);
17308   };
17309
17310   // Optimize shl/srl/sra with constant shift amount.
17311   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17312     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17313       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17314
17315       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17316         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17317
17318       // i64 SRA needs to be performed as partial shifts.
17319       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17320           Op.getOpcode() == ISD::SRA)
17321         return ArithmeticShiftRight64(ShiftAmt);
17322
17323       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17324         unsigned NumElts = VT.getVectorNumElements();
17325         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17326
17327         if (Op.getOpcode() == ISD::SHL) {
17328           // Simple i8 add case
17329           if (ShiftAmt == 1)
17330             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17331
17332           // Make a large shift.
17333           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17334                                                    R, ShiftAmt, DAG);
17335           SHL = DAG.getBitcast(VT, SHL);
17336           // Zero out the rightmost bits.
17337           SmallVector<SDValue, 32> V(
17338               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17339           return DAG.getNode(ISD::AND, dl, VT, SHL,
17340                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17341         }
17342         if (Op.getOpcode() == ISD::SRL) {
17343           // Make a large shift.
17344           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17345                                                    R, ShiftAmt, DAG);
17346           SRL = DAG.getBitcast(VT, SRL);
17347           // Zero out the leftmost bits.
17348           SmallVector<SDValue, 32> V(
17349               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17350           return DAG.getNode(ISD::AND, dl, VT, SRL,
17351                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17352         }
17353         if (Op.getOpcode() == ISD::SRA) {
17354           if (ShiftAmt == 7) {
17355             // ashr(R, 7)  === cmp_slt(R, 0)
17356             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17357             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17358           }
17359
17360           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17361           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17362           SmallVector<SDValue, 32> V(NumElts,
17363                                      DAG.getConstant(128 >> ShiftAmt, dl,
17364                                                      MVT::i8));
17365           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17366           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17367           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17368           return Res;
17369         }
17370         llvm_unreachable("Unknown shift opcode.");
17371       }
17372     }
17373   }
17374
17375   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17376   if (!Subtarget->is64Bit() &&
17377       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17378
17379     // Peek through any splat that was introduced for i64 shift vectorization.
17380     int SplatIndex = -1;
17381     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17382       if (SVN->isSplat()) {
17383         SplatIndex = SVN->getSplatIndex();
17384         Amt = Amt.getOperand(0);
17385         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17386                "Splat shuffle referencing second operand");
17387       }
17388
17389     if (Amt.getOpcode() != ISD::BITCAST ||
17390         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17391       return SDValue();
17392
17393     Amt = Amt.getOperand(0);
17394     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17395                      VT.getVectorNumElements();
17396     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17397     uint64_t ShiftAmt = 0;
17398     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17399     for (unsigned i = 0; i != Ratio; ++i) {
17400       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17401       if (!C)
17402         return SDValue();
17403       // 6 == Log2(64)
17404       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17405     }
17406
17407     // Check remaining shift amounts (if not a splat).
17408     if (SplatIndex < 0) {
17409       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17410         uint64_t ShAmt = 0;
17411         for (unsigned j = 0; j != Ratio; ++j) {
17412           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17413           if (!C)
17414             return SDValue();
17415           // 6 == Log2(64)
17416           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17417         }
17418         if (ShAmt != ShiftAmt)
17419           return SDValue();
17420       }
17421     }
17422
17423     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17424       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17425
17426     if (Op.getOpcode() == ISD::SRA)
17427       return ArithmeticShiftRight64(ShiftAmt);
17428   }
17429
17430   return SDValue();
17431 }
17432
17433 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17434                                         const X86Subtarget* Subtarget) {
17435   MVT VT = Op.getSimpleValueType();
17436   SDLoc dl(Op);
17437   SDValue R = Op.getOperand(0);
17438   SDValue Amt = Op.getOperand(1);
17439
17440   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17441     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17442
17443   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17444     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17445
17446   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17447     SDValue BaseShAmt;
17448     EVT EltVT = VT.getVectorElementType();
17449
17450     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17451       // Check if this build_vector node is doing a splat.
17452       // If so, then set BaseShAmt equal to the splat value.
17453       BaseShAmt = BV->getSplatValue();
17454       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17455         BaseShAmt = SDValue();
17456     } else {
17457       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17458         Amt = Amt.getOperand(0);
17459
17460       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17461       if (SVN && SVN->isSplat()) {
17462         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17463         SDValue InVec = Amt.getOperand(0);
17464         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17465           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17466                  "Unexpected shuffle index found!");
17467           BaseShAmt = InVec.getOperand(SplatIdx);
17468         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17469            if (ConstantSDNode *C =
17470                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17471              if (C->getZExtValue() == SplatIdx)
17472                BaseShAmt = InVec.getOperand(1);
17473            }
17474         }
17475
17476         if (!BaseShAmt)
17477           // Avoid introducing an extract element from a shuffle.
17478           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17479                                   DAG.getIntPtrConstant(SplatIdx, dl));
17480       }
17481     }
17482
17483     if (BaseShAmt.getNode()) {
17484       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17485       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17486         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17487       else if (EltVT.bitsLT(MVT::i32))
17488         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17489
17490       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17491     }
17492   }
17493
17494   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17495   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17496       Amt.getOpcode() == ISD::BITCAST &&
17497       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17498     Amt = Amt.getOperand(0);
17499     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17500                      VT.getVectorNumElements();
17501     std::vector<SDValue> Vals(Ratio);
17502     for (unsigned i = 0; i != Ratio; ++i)
17503       Vals[i] = Amt.getOperand(i);
17504     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17505       for (unsigned j = 0; j != Ratio; ++j)
17506         if (Vals[j] != Amt.getOperand(i + j))
17507           return SDValue();
17508     }
17509
17510     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17511       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17512   }
17513   return SDValue();
17514 }
17515
17516 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17517                           SelectionDAG &DAG) {
17518   MVT VT = Op.getSimpleValueType();
17519   SDLoc dl(Op);
17520   SDValue R = Op.getOperand(0);
17521   SDValue Amt = Op.getOperand(1);
17522
17523   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17524   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17525
17526   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17527     return V;
17528
17529   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17530       return V;
17531
17532   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17533     return Op;
17534
17535   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17536   // shifts per-lane and then shuffle the partial results back together.
17537   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17538     // Splat the shift amounts so the scalar shifts above will catch it.
17539     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17540     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17541     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17542     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17543     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17544   }
17545
17546   // i64 vector arithmetic shift can be emulated with the transform:
17547   // M = lshr(SIGN_BIT, Amt)
17548   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17549   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17550       Op.getOpcode() == ISD::SRA) {
17551     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17552     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17553     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17554     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17555     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17556     return R;
17557   }
17558
17559   // If possible, lower this packed shift into a vector multiply instead of
17560   // expanding it into a sequence of scalar shifts.
17561   // Do this only if the vector shift count is a constant build_vector.
17562   if (Op.getOpcode() == ISD::SHL &&
17563       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17564        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17565       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17566     SmallVector<SDValue, 8> Elts;
17567     EVT SVT = VT.getScalarType();
17568     unsigned SVTBits = SVT.getSizeInBits();
17569     const APInt &One = APInt(SVTBits, 1);
17570     unsigned NumElems = VT.getVectorNumElements();
17571
17572     for (unsigned i=0; i !=NumElems; ++i) {
17573       SDValue Op = Amt->getOperand(i);
17574       if (Op->getOpcode() == ISD::UNDEF) {
17575         Elts.push_back(Op);
17576         continue;
17577       }
17578
17579       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17580       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17581       uint64_t ShAmt = C.getZExtValue();
17582       if (ShAmt >= SVTBits) {
17583         Elts.push_back(DAG.getUNDEF(SVT));
17584         continue;
17585       }
17586       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17587     }
17588     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17589     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17590   }
17591
17592   // Lower SHL with variable shift amount.
17593   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17594     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17595
17596     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17597                      DAG.getConstant(0x3f800000U, dl, VT));
17598     Op = DAG.getBitcast(MVT::v4f32, Op);
17599     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17600     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17601   }
17602
17603   // If possible, lower this shift as a sequence of two shifts by
17604   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17605   // Example:
17606   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17607   //
17608   // Could be rewritten as:
17609   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17610   //
17611   // The advantage is that the two shifts from the example would be
17612   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17613   // the vector shift into four scalar shifts plus four pairs of vector
17614   // insert/extract.
17615   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17616       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17617     unsigned TargetOpcode = X86ISD::MOVSS;
17618     bool CanBeSimplified;
17619     // The splat value for the first packed shift (the 'X' from the example).
17620     SDValue Amt1 = Amt->getOperand(0);
17621     // The splat value for the second packed shift (the 'Y' from the example).
17622     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17623                                         Amt->getOperand(2);
17624
17625     // See if it is possible to replace this node with a sequence of
17626     // two shifts followed by a MOVSS/MOVSD
17627     if (VT == MVT::v4i32) {
17628       // Check if it is legal to use a MOVSS.
17629       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17630                         Amt2 == Amt->getOperand(3);
17631       if (!CanBeSimplified) {
17632         // Otherwise, check if we can still simplify this node using a MOVSD.
17633         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17634                           Amt->getOperand(2) == Amt->getOperand(3);
17635         TargetOpcode = X86ISD::MOVSD;
17636         Amt2 = Amt->getOperand(2);
17637       }
17638     } else {
17639       // Do similar checks for the case where the machine value type
17640       // is MVT::v8i16.
17641       CanBeSimplified = Amt1 == Amt->getOperand(1);
17642       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17643         CanBeSimplified = Amt2 == Amt->getOperand(i);
17644
17645       if (!CanBeSimplified) {
17646         TargetOpcode = X86ISD::MOVSD;
17647         CanBeSimplified = true;
17648         Amt2 = Amt->getOperand(4);
17649         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17650           CanBeSimplified = Amt1 == Amt->getOperand(i);
17651         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17652           CanBeSimplified = Amt2 == Amt->getOperand(j);
17653       }
17654     }
17655
17656     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17657         isa<ConstantSDNode>(Amt2)) {
17658       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17659       EVT CastVT = MVT::v4i32;
17660       SDValue Splat1 =
17661         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17662       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17663       SDValue Splat2 =
17664         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17665       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17666       if (TargetOpcode == X86ISD::MOVSD)
17667         CastVT = MVT::v2i64;
17668       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17669       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17670       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17671                                             BitCast1, DAG);
17672       return DAG.getBitcast(VT, Result);
17673     }
17674   }
17675
17676   // v4i32 Non Uniform Shifts.
17677   // If the shift amount is constant we can shift each lane using the SSE2
17678   // immediate shifts, else we need to zero-extend each lane to the lower i64
17679   // and shift using the SSE2 variable shifts.
17680   // The separate results can then be blended together.
17681   if (VT == MVT::v4i32) {
17682     unsigned Opc = Op.getOpcode();
17683     SDValue Amt0, Amt1, Amt2, Amt3;
17684     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17685       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17686       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17687       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17688       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17689     } else {
17690       // ISD::SHL is handled above but we include it here for completeness.
17691       switch (Opc) {
17692       default:
17693         llvm_unreachable("Unknown target vector shift node");
17694       case ISD::SHL:
17695         Opc = X86ISD::VSHL;
17696         break;
17697       case ISD::SRL:
17698         Opc = X86ISD::VSRL;
17699         break;
17700       case ISD::SRA:
17701         Opc = X86ISD::VSRA;
17702         break;
17703       }
17704       // The SSE2 shifts use the lower i64 as the same shift amount for
17705       // all lanes and the upper i64 is ignored. These shuffle masks
17706       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17707       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17708       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17709       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17710       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17711       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17712     }
17713
17714     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17715     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17716     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17717     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17718     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17719     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17720     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17721   }
17722
17723   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17724     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17725     unsigned ShiftOpcode = Op->getOpcode();
17726
17727     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17728       // On SSE41 targets we make use of the fact that VSELECT lowers
17729       // to PBLENDVB which selects bytes based just on the sign bit.
17730       if (Subtarget->hasSSE41()) {
17731         V0 = DAG.getBitcast(VT, V0);
17732         V1 = DAG.getBitcast(VT, V1);
17733         Sel = DAG.getBitcast(VT, Sel);
17734         return DAG.getBitcast(SelVT,
17735                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17736       }
17737       // On pre-SSE41 targets we test for the sign bit by comparing to
17738       // zero - a negative value will set all bits of the lanes to true
17739       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17740       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17741       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17742       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17743     };
17744
17745     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17746     // We can safely do this using i16 shifts as we're only interested in
17747     // the 3 lower bits of each byte.
17748     Amt = DAG.getBitcast(ExtVT, Amt);
17749     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17750     Amt = DAG.getBitcast(VT, Amt);
17751
17752     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17753       // r = VSELECT(r, shift(r, 4), a);
17754       SDValue M =
17755           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17756       R = SignBitSelect(VT, Amt, M, R);
17757
17758       // a += a
17759       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17760
17761       // r = VSELECT(r, shift(r, 2), a);
17762       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17763       R = SignBitSelect(VT, Amt, M, R);
17764
17765       // a += a
17766       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17767
17768       // return VSELECT(r, shift(r, 1), a);
17769       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17770       R = SignBitSelect(VT, Amt, M, R);
17771       return R;
17772     }
17773
17774     if (Op->getOpcode() == ISD::SRA) {
17775       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17776       // so we can correctly sign extend. We don't care what happens to the
17777       // lower byte.
17778       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17779       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17780       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17781       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17782       ALo = DAG.getBitcast(ExtVT, ALo);
17783       AHi = DAG.getBitcast(ExtVT, AHi);
17784       RLo = DAG.getBitcast(ExtVT, RLo);
17785       RHi = DAG.getBitcast(ExtVT, RHi);
17786
17787       // r = VSELECT(r, shift(r, 4), a);
17788       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17789                                 DAG.getConstant(4, dl, ExtVT));
17790       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17791                                 DAG.getConstant(4, dl, ExtVT));
17792       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17793       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17794
17795       // a += a
17796       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17797       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17798
17799       // r = VSELECT(r, shift(r, 2), a);
17800       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17801                         DAG.getConstant(2, dl, ExtVT));
17802       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17803                         DAG.getConstant(2, dl, ExtVT));
17804       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17805       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17806
17807       // a += a
17808       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17809       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17810
17811       // r = VSELECT(r, shift(r, 1), a);
17812       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17813                         DAG.getConstant(1, dl, ExtVT));
17814       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17815                         DAG.getConstant(1, dl, ExtVT));
17816       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17817       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17818
17819       // Logical shift the result back to the lower byte, leaving a zero upper
17820       // byte
17821       // meaning that we can safely pack with PACKUSWB.
17822       RLo =
17823           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17824       RHi =
17825           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17826       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17827     }
17828   }
17829
17830   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17831   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17832   // solution better.
17833   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17834     MVT ExtVT = MVT::v8i32;
17835     unsigned ExtOpc =
17836         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17837     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17838     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17839     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17840                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17841   }
17842
17843   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17844     MVT ExtVT = MVT::v8i32;
17845     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17846     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17847     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17848     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17849     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17850     ALo = DAG.getBitcast(ExtVT, ALo);
17851     AHi = DAG.getBitcast(ExtVT, AHi);
17852     RLo = DAG.getBitcast(ExtVT, RLo);
17853     RHi = DAG.getBitcast(ExtVT, RHi);
17854     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17855     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17856     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17857     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17858     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17859   }
17860
17861   if (VT == MVT::v8i16) {
17862     unsigned ShiftOpcode = Op->getOpcode();
17863
17864     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17865       // On SSE41 targets we make use of the fact that VSELECT lowers
17866       // to PBLENDVB which selects bytes based just on the sign bit.
17867       if (Subtarget->hasSSE41()) {
17868         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17869         V0 = DAG.getBitcast(ExtVT, V0);
17870         V1 = DAG.getBitcast(ExtVT, V1);
17871         Sel = DAG.getBitcast(ExtVT, Sel);
17872         return DAG.getBitcast(
17873             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17874       }
17875       // On pre-SSE41 targets we splat the sign bit - a negative value will
17876       // set all bits of the lanes to true and VSELECT uses that in
17877       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17878       SDValue C =
17879           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17880       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17881     };
17882
17883     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17884     if (Subtarget->hasSSE41()) {
17885       // On SSE41 targets we need to replicate the shift mask in both
17886       // bytes for PBLENDVB.
17887       Amt = DAG.getNode(
17888           ISD::OR, dl, VT,
17889           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17890           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17891     } else {
17892       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17893     }
17894
17895     // r = VSELECT(r, shift(r, 8), a);
17896     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17897     R = SignBitSelect(Amt, M, R);
17898
17899     // a += a
17900     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17901
17902     // r = VSELECT(r, shift(r, 4), a);
17903     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17904     R = SignBitSelect(Amt, M, R);
17905
17906     // a += a
17907     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17908
17909     // r = VSELECT(r, shift(r, 2), a);
17910     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17911     R = SignBitSelect(Amt, M, R);
17912
17913     // a += a
17914     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17915
17916     // return VSELECT(r, shift(r, 1), a);
17917     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17918     R = SignBitSelect(Amt, M, R);
17919     return R;
17920   }
17921
17922   // Decompose 256-bit shifts into smaller 128-bit shifts.
17923   if (VT.is256BitVector()) {
17924     unsigned NumElems = VT.getVectorNumElements();
17925     MVT EltVT = VT.getVectorElementType();
17926     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17927
17928     // Extract the two vectors
17929     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17930     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17931
17932     // Recreate the shift amount vectors
17933     SDValue Amt1, Amt2;
17934     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17935       // Constant shift amount
17936       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17937       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17938       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17939
17940       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17941       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17942     } else {
17943       // Variable shift amount
17944       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17945       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17946     }
17947
17948     // Issue new vector shifts for the smaller types
17949     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17950     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17951
17952     // Concatenate the result back
17953     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17954   }
17955
17956   return SDValue();
17957 }
17958
17959 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17960   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17961   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17962   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17963   // has only one use.
17964   SDNode *N = Op.getNode();
17965   SDValue LHS = N->getOperand(0);
17966   SDValue RHS = N->getOperand(1);
17967   unsigned BaseOp = 0;
17968   unsigned Cond = 0;
17969   SDLoc DL(Op);
17970   switch (Op.getOpcode()) {
17971   default: llvm_unreachable("Unknown ovf instruction!");
17972   case ISD::SADDO:
17973     // A subtract of one will be selected as a INC. Note that INC doesn't
17974     // set CF, so we can't do this for UADDO.
17975     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17976       if (C->isOne()) {
17977         BaseOp = X86ISD::INC;
17978         Cond = X86::COND_O;
17979         break;
17980       }
17981     BaseOp = X86ISD::ADD;
17982     Cond = X86::COND_O;
17983     break;
17984   case ISD::UADDO:
17985     BaseOp = X86ISD::ADD;
17986     Cond = X86::COND_B;
17987     break;
17988   case ISD::SSUBO:
17989     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17990     // set CF, so we can't do this for USUBO.
17991     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17992       if (C->isOne()) {
17993         BaseOp = X86ISD::DEC;
17994         Cond = X86::COND_O;
17995         break;
17996       }
17997     BaseOp = X86ISD::SUB;
17998     Cond = X86::COND_O;
17999     break;
18000   case ISD::USUBO:
18001     BaseOp = X86ISD::SUB;
18002     Cond = X86::COND_B;
18003     break;
18004   case ISD::SMULO:
18005     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18006     Cond = X86::COND_O;
18007     break;
18008   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18009     if (N->getValueType(0) == MVT::i8) {
18010       BaseOp = X86ISD::UMUL8;
18011       Cond = X86::COND_O;
18012       break;
18013     }
18014     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18015                                  MVT::i32);
18016     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18017
18018     SDValue SetCC =
18019       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18020                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18021                   SDValue(Sum.getNode(), 2));
18022
18023     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18024   }
18025   }
18026
18027   // Also sets EFLAGS.
18028   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18029   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18030
18031   SDValue SetCC =
18032     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18033                 DAG.getConstant(Cond, DL, MVT::i32),
18034                 SDValue(Sum.getNode(), 1));
18035
18036   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18037 }
18038
18039 /// Returns true if the operand type is exactly twice the native width, and
18040 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18041 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18042 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18043 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18044   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18045
18046   if (OpWidth == 64)
18047     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18048   else if (OpWidth == 128)
18049     return Subtarget->hasCmpxchg16b();
18050   else
18051     return false;
18052 }
18053
18054 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18055   return needsCmpXchgNb(SI->getValueOperand()->getType());
18056 }
18057
18058 // Note: this turns large loads into lock cmpxchg8b/16b.
18059 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18060 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18061   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18062   return needsCmpXchgNb(PTy->getElementType());
18063 }
18064
18065 TargetLoweringBase::AtomicRMWExpansionKind
18066 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18067   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18068   Type *MemType = AI->getType();
18069
18070   // If the operand is too big, we must see if cmpxchg8/16b is available
18071   // and default to library calls otherwise.
18072   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18073     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18074                                    : AtomicRMWExpansionKind::None;
18075   }
18076
18077   AtomicRMWInst::BinOp Op = AI->getOperation();
18078   switch (Op) {
18079   default:
18080     llvm_unreachable("Unknown atomic operation");
18081   case AtomicRMWInst::Xchg:
18082   case AtomicRMWInst::Add:
18083   case AtomicRMWInst::Sub:
18084     // It's better to use xadd, xsub or xchg for these in all cases.
18085     return AtomicRMWExpansionKind::None;
18086   case AtomicRMWInst::Or:
18087   case AtomicRMWInst::And:
18088   case AtomicRMWInst::Xor:
18089     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18090     // prefix to a normal instruction for these operations.
18091     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18092                             : AtomicRMWExpansionKind::None;
18093   case AtomicRMWInst::Nand:
18094   case AtomicRMWInst::Max:
18095   case AtomicRMWInst::Min:
18096   case AtomicRMWInst::UMax:
18097   case AtomicRMWInst::UMin:
18098     // These always require a non-trivial set of data operations on x86. We must
18099     // use a cmpxchg loop.
18100     return AtomicRMWExpansionKind::CmpXChg;
18101   }
18102 }
18103
18104 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18105   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18106   // no-sse2). There isn't any reason to disable it if the target processor
18107   // supports it.
18108   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18109 }
18110
18111 LoadInst *
18112 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18113   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18114   Type *MemType = AI->getType();
18115   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18116   // there is no benefit in turning such RMWs into loads, and it is actually
18117   // harmful as it introduces a mfence.
18118   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18119     return nullptr;
18120
18121   auto Builder = IRBuilder<>(AI);
18122   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18123   auto SynchScope = AI->getSynchScope();
18124   // We must restrict the ordering to avoid generating loads with Release or
18125   // ReleaseAcquire orderings.
18126   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18127   auto Ptr = AI->getPointerOperand();
18128
18129   // Before the load we need a fence. Here is an example lifted from
18130   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18131   // is required:
18132   // Thread 0:
18133   //   x.store(1, relaxed);
18134   //   r1 = y.fetch_add(0, release);
18135   // Thread 1:
18136   //   y.fetch_add(42, acquire);
18137   //   r2 = x.load(relaxed);
18138   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18139   // lowered to just a load without a fence. A mfence flushes the store buffer,
18140   // making the optimization clearly correct.
18141   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18142   // otherwise, we might be able to be more aggressive on relaxed idempotent
18143   // rmw. In practice, they do not look useful, so we don't try to be
18144   // especially clever.
18145   if (SynchScope == SingleThread)
18146     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18147     // the IR level, so we must wrap it in an intrinsic.
18148     return nullptr;
18149
18150   if (!hasMFENCE(*Subtarget))
18151     // FIXME: it might make sense to use a locked operation here but on a
18152     // different cache-line to prevent cache-line bouncing. In practice it
18153     // is probably a small win, and x86 processors without mfence are rare
18154     // enough that we do not bother.
18155     return nullptr;
18156
18157   Function *MFence =
18158       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18159   Builder.CreateCall(MFence, {});
18160
18161   // Finally we can emit the atomic load.
18162   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18163           AI->getType()->getPrimitiveSizeInBits());
18164   Loaded->setAtomic(Order, SynchScope);
18165   AI->replaceAllUsesWith(Loaded);
18166   AI->eraseFromParent();
18167   return Loaded;
18168 }
18169
18170 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18171                                  SelectionDAG &DAG) {
18172   SDLoc dl(Op);
18173   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18174     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18175   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18176     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18177
18178   // The only fence that needs an instruction is a sequentially-consistent
18179   // cross-thread fence.
18180   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18181     if (hasMFENCE(*Subtarget))
18182       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18183
18184     SDValue Chain = Op.getOperand(0);
18185     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18186     SDValue Ops[] = {
18187       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18188       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18189       DAG.getRegister(0, MVT::i32),            // Index
18190       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18191       DAG.getRegister(0, MVT::i32),            // Segment.
18192       Zero,
18193       Chain
18194     };
18195     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18196     return SDValue(Res, 0);
18197   }
18198
18199   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18200   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18201 }
18202
18203 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18204                              SelectionDAG &DAG) {
18205   MVT T = Op.getSimpleValueType();
18206   SDLoc DL(Op);
18207   unsigned Reg = 0;
18208   unsigned size = 0;
18209   switch(T.SimpleTy) {
18210   default: llvm_unreachable("Invalid value type!");
18211   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18212   case MVT::i16: Reg = X86::AX;  size = 2; break;
18213   case MVT::i32: Reg = X86::EAX; size = 4; break;
18214   case MVT::i64:
18215     assert(Subtarget->is64Bit() && "Node not type legal!");
18216     Reg = X86::RAX; size = 8;
18217     break;
18218   }
18219   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18220                                   Op.getOperand(2), SDValue());
18221   SDValue Ops[] = { cpIn.getValue(0),
18222                     Op.getOperand(1),
18223                     Op.getOperand(3),
18224                     DAG.getTargetConstant(size, DL, MVT::i8),
18225                     cpIn.getValue(1) };
18226   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18227   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18228   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18229                                            Ops, T, MMO);
18230
18231   SDValue cpOut =
18232     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18233   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18234                                       MVT::i32, cpOut.getValue(2));
18235   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18236                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18237                                 EFLAGS);
18238
18239   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18240   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18241   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18242   return SDValue();
18243 }
18244
18245 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18246                             SelectionDAG &DAG) {
18247   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18248   MVT DstVT = Op.getSimpleValueType();
18249
18250   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18251     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18252     if (DstVT != MVT::f64)
18253       // This conversion needs to be expanded.
18254       return SDValue();
18255
18256     SDValue InVec = Op->getOperand(0);
18257     SDLoc dl(Op);
18258     unsigned NumElts = SrcVT.getVectorNumElements();
18259     EVT SVT = SrcVT.getVectorElementType();
18260
18261     // Widen the vector in input in the case of MVT::v2i32.
18262     // Example: from MVT::v2i32 to MVT::v4i32.
18263     SmallVector<SDValue, 16> Elts;
18264     for (unsigned i = 0, e = NumElts; i != e; ++i)
18265       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18266                                  DAG.getIntPtrConstant(i, dl)));
18267
18268     // Explicitly mark the extra elements as Undef.
18269     Elts.append(NumElts, DAG.getUNDEF(SVT));
18270
18271     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18272     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18273     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18274     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18275                        DAG.getIntPtrConstant(0, dl));
18276   }
18277
18278   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18279          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18280   assert((DstVT == MVT::i64 ||
18281           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18282          "Unexpected custom BITCAST");
18283   // i64 <=> MMX conversions are Legal.
18284   if (SrcVT==MVT::i64 && DstVT.isVector())
18285     return Op;
18286   if (DstVT==MVT::i64 && SrcVT.isVector())
18287     return Op;
18288   // MMX <=> MMX conversions are Legal.
18289   if (SrcVT.isVector() && DstVT.isVector())
18290     return Op;
18291   // All other conversions need to be expanded.
18292   return SDValue();
18293 }
18294
18295 /// Compute the horizontal sum of bytes in V for the elements of VT.
18296 ///
18297 /// Requires V to be a byte vector and VT to be an integer vector type with
18298 /// wider elements than V's type. The width of the elements of VT determines
18299 /// how many bytes of V are summed horizontally to produce each element of the
18300 /// result.
18301 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18302                                       const X86Subtarget *Subtarget,
18303                                       SelectionDAG &DAG) {
18304   SDLoc DL(V);
18305   MVT ByteVecVT = V.getSimpleValueType();
18306   MVT EltVT = VT.getVectorElementType();
18307   int NumElts = VT.getVectorNumElements();
18308   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18309          "Expected value to have byte element type.");
18310   assert(EltVT != MVT::i8 &&
18311          "Horizontal byte sum only makes sense for wider elements!");
18312   unsigned VecSize = VT.getSizeInBits();
18313   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18314
18315   // PSADBW instruction horizontally add all bytes and leave the result in i64
18316   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18317   if (EltVT == MVT::i64) {
18318     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18319     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18320     return DAG.getBitcast(VT, V);
18321   }
18322
18323   if (EltVT == MVT::i32) {
18324     // We unpack the low half and high half into i32s interleaved with zeros so
18325     // that we can use PSADBW to horizontally sum them. The most useful part of
18326     // this is that it lines up the results of two PSADBW instructions to be
18327     // two v2i64 vectors which concatenated are the 4 population counts. We can
18328     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18329     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18330     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18331     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18332
18333     // Do the horizontal sums into two v2i64s.
18334     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18335     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18336                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18337     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18338                        DAG.getBitcast(ByteVecVT, High), Zeros);
18339
18340     // Merge them together.
18341     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18342     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18343                     DAG.getBitcast(ShortVecVT, Low),
18344                     DAG.getBitcast(ShortVecVT, High));
18345
18346     return DAG.getBitcast(VT, V);
18347   }
18348
18349   // The only element type left is i16.
18350   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18351
18352   // To obtain pop count for each i16 element starting from the pop count for
18353   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18354   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18355   // directly supported.
18356   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18357   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18358   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18359   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18360                   DAG.getBitcast(ByteVecVT, V));
18361   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18362 }
18363
18364 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18365                                         const X86Subtarget *Subtarget,
18366                                         SelectionDAG &DAG) {
18367   MVT VT = Op.getSimpleValueType();
18368   MVT EltVT = VT.getVectorElementType();
18369   unsigned VecSize = VT.getSizeInBits();
18370
18371   // Implement a lookup table in register by using an algorithm based on:
18372   // http://wm.ite.pl/articles/sse-popcount.html
18373   //
18374   // The general idea is that every lower byte nibble in the input vector is an
18375   // index into a in-register pre-computed pop count table. We then split up the
18376   // input vector in two new ones: (1) a vector with only the shifted-right
18377   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18378   // masked out higher ones) for each byte. PSHUB is used separately with both
18379   // to index the in-register table. Next, both are added and the result is a
18380   // i8 vector where each element contains the pop count for input byte.
18381   //
18382   // To obtain the pop count for elements != i8, we follow up with the same
18383   // approach and use additional tricks as described below.
18384   //
18385   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18386                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18387                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18388                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18389
18390   int NumByteElts = VecSize / 8;
18391   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18392   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18393   SmallVector<SDValue, 16> LUTVec;
18394   for (int i = 0; i < NumByteElts; ++i)
18395     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18396   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18397   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18398                                   DAG.getConstant(0x0F, DL, MVT::i8));
18399   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18400
18401   // High nibbles
18402   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18403   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18404   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18405
18406   // Low nibbles
18407   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18408
18409   // The input vector is used as the shuffle mask that index elements into the
18410   // LUT. After counting low and high nibbles, add the vector to obtain the
18411   // final pop count per i8 element.
18412   SDValue HighPopCnt =
18413       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18414   SDValue LowPopCnt =
18415       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18416   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18417
18418   if (EltVT == MVT::i8)
18419     return PopCnt;
18420
18421   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18422 }
18423
18424 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18425                                        const X86Subtarget *Subtarget,
18426                                        SelectionDAG &DAG) {
18427   MVT VT = Op.getSimpleValueType();
18428   assert(VT.is128BitVector() &&
18429          "Only 128-bit vector bitmath lowering supported.");
18430
18431   int VecSize = VT.getSizeInBits();
18432   MVT EltVT = VT.getVectorElementType();
18433   int Len = EltVT.getSizeInBits();
18434
18435   // This is the vectorized version of the "best" algorithm from
18436   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18437   // with a minor tweak to use a series of adds + shifts instead of vector
18438   // multiplications. Implemented for all integer vector types. We only use
18439   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18440   // much faster, even faster than using native popcnt instructions.
18441
18442   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18443     MVT VT = V.getSimpleValueType();
18444     SmallVector<SDValue, 32> Shifters(
18445         VT.getVectorNumElements(),
18446         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18447     return DAG.getNode(OpCode, DL, VT, V,
18448                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18449   };
18450   auto GetMask = [&](SDValue V, APInt Mask) {
18451     MVT VT = V.getSimpleValueType();
18452     SmallVector<SDValue, 32> Masks(
18453         VT.getVectorNumElements(),
18454         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18455     return DAG.getNode(ISD::AND, DL, VT, V,
18456                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18457   };
18458
18459   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18460   // x86, so set the SRL type to have elements at least i16 wide. This is
18461   // correct because all of our SRLs are followed immediately by a mask anyways
18462   // that handles any bits that sneak into the high bits of the byte elements.
18463   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18464
18465   SDValue V = Op;
18466
18467   // v = v - ((v >> 1) & 0x55555555...)
18468   SDValue Srl =
18469       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18470   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18471   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18472
18473   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18474   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18475   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18476   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18477   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18478
18479   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18480   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18481   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18482   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18483
18484   // At this point, V contains the byte-wise population count, and we are
18485   // merely doing a horizontal sum if necessary to get the wider element
18486   // counts.
18487   if (EltVT == MVT::i8)
18488     return V;
18489
18490   return LowerHorizontalByteSum(
18491       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18492       DAG);
18493 }
18494
18495 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18496                                 SelectionDAG &DAG) {
18497   MVT VT = Op.getSimpleValueType();
18498   // FIXME: Need to add AVX-512 support here!
18499   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18500          "Unknown CTPOP type to handle");
18501   SDLoc DL(Op.getNode());
18502   SDValue Op0 = Op.getOperand(0);
18503
18504   if (!Subtarget->hasSSSE3()) {
18505     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18506     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18507     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18508   }
18509
18510   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18511     unsigned NumElems = VT.getVectorNumElements();
18512
18513     // Extract each 128-bit vector, compute pop count and concat the result.
18514     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18515     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18516
18517     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18518                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18519                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18520   }
18521
18522   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18523 }
18524
18525 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18526                           SelectionDAG &DAG) {
18527   assert(Op.getValueType().isVector() &&
18528          "We only do custom lowering for vector population count.");
18529   return LowerVectorCTPOP(Op, Subtarget, DAG);
18530 }
18531
18532 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18533   SDNode *Node = Op.getNode();
18534   SDLoc dl(Node);
18535   EVT T = Node->getValueType(0);
18536   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18537                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18538   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18539                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18540                        Node->getOperand(0),
18541                        Node->getOperand(1), negOp,
18542                        cast<AtomicSDNode>(Node)->getMemOperand(),
18543                        cast<AtomicSDNode>(Node)->getOrdering(),
18544                        cast<AtomicSDNode>(Node)->getSynchScope());
18545 }
18546
18547 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18548   SDNode *Node = Op.getNode();
18549   SDLoc dl(Node);
18550   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18551
18552   // Convert seq_cst store -> xchg
18553   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18554   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18555   //        (The only way to get a 16-byte store is cmpxchg16b)
18556   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18557   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18558       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18559     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18560                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18561                                  Node->getOperand(0),
18562                                  Node->getOperand(1), Node->getOperand(2),
18563                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18564                                  cast<AtomicSDNode>(Node)->getOrdering(),
18565                                  cast<AtomicSDNode>(Node)->getSynchScope());
18566     return Swap.getValue(1);
18567   }
18568   // Other atomic stores have a simple pattern.
18569   return Op;
18570 }
18571
18572 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18573   EVT VT = Op.getNode()->getSimpleValueType(0);
18574
18575   // Let legalize expand this if it isn't a legal type yet.
18576   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18577     return SDValue();
18578
18579   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18580
18581   unsigned Opc;
18582   bool ExtraOp = false;
18583   switch (Op.getOpcode()) {
18584   default: llvm_unreachable("Invalid code");
18585   case ISD::ADDC: Opc = X86ISD::ADD; break;
18586   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18587   case ISD::SUBC: Opc = X86ISD::SUB; break;
18588   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18589   }
18590
18591   if (!ExtraOp)
18592     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18593                        Op.getOperand(1));
18594   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18595                      Op.getOperand(1), Op.getOperand(2));
18596 }
18597
18598 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18599                             SelectionDAG &DAG) {
18600   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18601
18602   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18603   // which returns the values as { float, float } (in XMM0) or
18604   // { double, double } (which is returned in XMM0, XMM1).
18605   SDLoc dl(Op);
18606   SDValue Arg = Op.getOperand(0);
18607   EVT ArgVT = Arg.getValueType();
18608   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18609
18610   TargetLowering::ArgListTy Args;
18611   TargetLowering::ArgListEntry Entry;
18612
18613   Entry.Node = Arg;
18614   Entry.Ty = ArgTy;
18615   Entry.isSExt = false;
18616   Entry.isZExt = false;
18617   Args.push_back(Entry);
18618
18619   bool isF64 = ArgVT == MVT::f64;
18620   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18621   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18622   // the results are returned via SRet in memory.
18623   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18625   SDValue Callee =
18626       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18627
18628   Type *RetTy = isF64
18629     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18630     : (Type*)VectorType::get(ArgTy, 4);
18631
18632   TargetLowering::CallLoweringInfo CLI(DAG);
18633   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18634     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18635
18636   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18637
18638   if (isF64)
18639     // Returned in xmm0 and xmm1.
18640     return CallResult.first;
18641
18642   // Returned in bits 0:31 and 32:64 xmm0.
18643   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18644                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18645   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18646                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18647   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18648   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18649 }
18650
18651 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18652                              SelectionDAG &DAG) {
18653   assert(Subtarget->hasAVX512() &&
18654          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18655
18656   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18657   EVT VT = N->getValue().getValueType();
18658   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18659   SDLoc dl(Op);
18660
18661   // X86 scatter kills mask register, so its type should be added to
18662   // the list of return values
18663   if (N->getNumValues() == 1) {
18664     SDValue Index = N->getIndex();
18665     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18666         !Index.getValueType().is512BitVector())
18667       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18668
18669     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18670     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18671                       N->getOperand(3), Index };
18672
18673     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18674     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18675     return SDValue(NewScatter.getNode(), 0);
18676   }
18677   return Op;
18678 }
18679
18680 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18681                             SelectionDAG &DAG) {
18682   assert(Subtarget->hasAVX512() &&
18683          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18684
18685   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18686   EVT VT = Op.getValueType();
18687   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18688   SDLoc dl(Op);
18689
18690   SDValue Index = N->getIndex();
18691   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18692       !Index.getValueType().is512BitVector()) {
18693     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18694     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18695                       N->getOperand(3), Index };
18696     DAG.UpdateNodeOperands(N, Ops);
18697   }
18698   return Op;
18699 }
18700
18701 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18702                                                     SelectionDAG &DAG) const {
18703   // TODO: Eventually, the lowering of these nodes should be informed by or
18704   // deferred to the GC strategy for the function in which they appear. For
18705   // now, however, they must be lowered to something. Since they are logically
18706   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18707   // require special handling for these nodes), lower them as literal NOOPs for
18708   // the time being.
18709   SmallVector<SDValue, 2> Ops;
18710
18711   Ops.push_back(Op.getOperand(0));
18712   if (Op->getGluedNode())
18713     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18714
18715   SDLoc OpDL(Op);
18716   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18717   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18718
18719   return NOOP;
18720 }
18721
18722 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18723                                                   SelectionDAG &DAG) const {
18724   // TODO: Eventually, the lowering of these nodes should be informed by or
18725   // deferred to the GC strategy for the function in which they appear. For
18726   // now, however, they must be lowered to something. Since they are logically
18727   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18728   // require special handling for these nodes), lower them as literal NOOPs for
18729   // the time being.
18730   SmallVector<SDValue, 2> Ops;
18731
18732   Ops.push_back(Op.getOperand(0));
18733   if (Op->getGluedNode())
18734     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18735
18736   SDLoc OpDL(Op);
18737   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18738   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18739
18740   return NOOP;
18741 }
18742
18743 /// LowerOperation - Provide custom lowering hooks for some operations.
18744 ///
18745 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18746   switch (Op.getOpcode()) {
18747   default: llvm_unreachable("Should not custom lower this!");
18748   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18749   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18750     return LowerCMP_SWAP(Op, Subtarget, DAG);
18751   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18752   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18753   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18754   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18755   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18756   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18757   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18758   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18759   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18760   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18761   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18762   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18763   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18764   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18765   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18766   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18767   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18768   case ISD::SHL_PARTS:
18769   case ISD::SRA_PARTS:
18770   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18771   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18772   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18773   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18774   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18775   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18776   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18777   case ISD::SIGN_EXTEND_VECTOR_INREG:
18778     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18779   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18780   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18781   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18782   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18783   case ISD::FABS:
18784   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18785   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18786   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18787   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18788   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18789   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18790   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18791   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18792   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18793   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18794   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18795   case ISD::INTRINSIC_VOID:
18796   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18797   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18798   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18799   case ISD::FRAME_TO_ARGS_OFFSET:
18800                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18801   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18802   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18803   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18804   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18805   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18806   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18807   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18808   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18809   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18810   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18811   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18812   case ISD::UMUL_LOHI:
18813   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18814   case ISD::SRA:
18815   case ISD::SRL:
18816   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18817   case ISD::SADDO:
18818   case ISD::UADDO:
18819   case ISD::SSUBO:
18820   case ISD::USUBO:
18821   case ISD::SMULO:
18822   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18823   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18824   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18825   case ISD::ADDC:
18826   case ISD::ADDE:
18827   case ISD::SUBC:
18828   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18829   case ISD::ADD:                return LowerADD(Op, DAG);
18830   case ISD::SUB:                return LowerSUB(Op, DAG);
18831   case ISD::SMAX:
18832   case ISD::SMIN:
18833   case ISD::UMAX:
18834   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18835   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18836   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18837   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18838   case ISD::GC_TRANSITION_START:
18839                                 return LowerGC_TRANSITION_START(Op, DAG);
18840   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18841   }
18842 }
18843
18844 /// ReplaceNodeResults - Replace a node with an illegal result type
18845 /// with a new node built out of custom code.
18846 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18847                                            SmallVectorImpl<SDValue>&Results,
18848                                            SelectionDAG &DAG) const {
18849   SDLoc dl(N);
18850   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18851   switch (N->getOpcode()) {
18852   default:
18853     llvm_unreachable("Do not know how to custom type legalize this operation!");
18854   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18855   case X86ISD::FMINC:
18856   case X86ISD::FMIN:
18857   case X86ISD::FMAXC:
18858   case X86ISD::FMAX: {
18859     EVT VT = N->getValueType(0);
18860     if (VT != MVT::v2f32)
18861       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18862     SDValue UNDEF = DAG.getUNDEF(VT);
18863     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18864                               N->getOperand(0), UNDEF);
18865     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18866                               N->getOperand(1), UNDEF);
18867     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18868     return;
18869   }
18870   case ISD::SIGN_EXTEND_INREG:
18871   case ISD::ADDC:
18872   case ISD::ADDE:
18873   case ISD::SUBC:
18874   case ISD::SUBE:
18875     // We don't want to expand or promote these.
18876     return;
18877   case ISD::SDIV:
18878   case ISD::UDIV:
18879   case ISD::SREM:
18880   case ISD::UREM:
18881   case ISD::SDIVREM:
18882   case ISD::UDIVREM: {
18883     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18884     Results.push_back(V);
18885     return;
18886   }
18887   case ISD::FP_TO_SINT:
18888     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18889     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18890     if (N->getOperand(0).getValueType() == MVT::f16)
18891       break;
18892     // fallthrough
18893   case ISD::FP_TO_UINT: {
18894     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18895
18896     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18897       return;
18898
18899     std::pair<SDValue,SDValue> Vals =
18900         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18901     SDValue FIST = Vals.first, StackSlot = Vals.second;
18902     if (FIST.getNode()) {
18903       EVT VT = N->getValueType(0);
18904       // Return a load from the stack slot.
18905       if (StackSlot.getNode())
18906         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18907                                       MachinePointerInfo(),
18908                                       false, false, false, 0));
18909       else
18910         Results.push_back(FIST);
18911     }
18912     return;
18913   }
18914   case ISD::UINT_TO_FP: {
18915     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18916     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18917         N->getValueType(0) != MVT::v2f32)
18918       return;
18919     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18920                                  N->getOperand(0));
18921     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18922                                      MVT::f64);
18923     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18924     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18925                              DAG.getBitcast(MVT::v2i64, VBias));
18926     Or = DAG.getBitcast(MVT::v2f64, Or);
18927     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18928     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18929     return;
18930   }
18931   case ISD::FP_ROUND: {
18932     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18933         return;
18934     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18935     Results.push_back(V);
18936     return;
18937   }
18938   case ISD::FP_EXTEND: {
18939     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18940     // No other ValueType for FP_EXTEND should reach this point.
18941     assert(N->getValueType(0) == MVT::v2f32 &&
18942            "Do not know how to legalize this Node");
18943     return;
18944   }
18945   case ISD::INTRINSIC_W_CHAIN: {
18946     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18947     switch (IntNo) {
18948     default : llvm_unreachable("Do not know how to custom type "
18949                                "legalize this intrinsic operation!");
18950     case Intrinsic::x86_rdtsc:
18951       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18952                                      Results);
18953     case Intrinsic::x86_rdtscp:
18954       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18955                                      Results);
18956     case Intrinsic::x86_rdpmc:
18957       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18958     }
18959   }
18960   case ISD::READCYCLECOUNTER: {
18961     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18962                                    Results);
18963   }
18964   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18965     EVT T = N->getValueType(0);
18966     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18967     bool Regs64bit = T == MVT::i128;
18968     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18969     SDValue cpInL, cpInH;
18970     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18971                         DAG.getConstant(0, dl, HalfT));
18972     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18973                         DAG.getConstant(1, dl, HalfT));
18974     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18975                              Regs64bit ? X86::RAX : X86::EAX,
18976                              cpInL, SDValue());
18977     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18978                              Regs64bit ? X86::RDX : X86::EDX,
18979                              cpInH, cpInL.getValue(1));
18980     SDValue swapInL, swapInH;
18981     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18982                           DAG.getConstant(0, dl, HalfT));
18983     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18984                           DAG.getConstant(1, dl, HalfT));
18985     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18986                                Regs64bit ? X86::RBX : X86::EBX,
18987                                swapInL, cpInH.getValue(1));
18988     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18989                                Regs64bit ? X86::RCX : X86::ECX,
18990                                swapInH, swapInL.getValue(1));
18991     SDValue Ops[] = { swapInH.getValue(0),
18992                       N->getOperand(1),
18993                       swapInH.getValue(1) };
18994     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18995     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18996     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18997                                   X86ISD::LCMPXCHG8_DAG;
18998     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18999     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19000                                         Regs64bit ? X86::RAX : X86::EAX,
19001                                         HalfT, Result.getValue(1));
19002     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19003                                         Regs64bit ? X86::RDX : X86::EDX,
19004                                         HalfT, cpOutL.getValue(2));
19005     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19006
19007     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19008                                         MVT::i32, cpOutH.getValue(2));
19009     SDValue Success =
19010         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19011                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19012     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19013
19014     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19015     Results.push_back(Success);
19016     Results.push_back(EFLAGS.getValue(1));
19017     return;
19018   }
19019   case ISD::ATOMIC_SWAP:
19020   case ISD::ATOMIC_LOAD_ADD:
19021   case ISD::ATOMIC_LOAD_SUB:
19022   case ISD::ATOMIC_LOAD_AND:
19023   case ISD::ATOMIC_LOAD_OR:
19024   case ISD::ATOMIC_LOAD_XOR:
19025   case ISD::ATOMIC_LOAD_NAND:
19026   case ISD::ATOMIC_LOAD_MIN:
19027   case ISD::ATOMIC_LOAD_MAX:
19028   case ISD::ATOMIC_LOAD_UMIN:
19029   case ISD::ATOMIC_LOAD_UMAX:
19030   case ISD::ATOMIC_LOAD: {
19031     // Delegate to generic TypeLegalization. Situations we can really handle
19032     // should have already been dealt with by AtomicExpandPass.cpp.
19033     break;
19034   }
19035   case ISD::BITCAST: {
19036     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19037     EVT DstVT = N->getValueType(0);
19038     EVT SrcVT = N->getOperand(0)->getValueType(0);
19039
19040     if (SrcVT != MVT::f64 ||
19041         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19042       return;
19043
19044     unsigned NumElts = DstVT.getVectorNumElements();
19045     EVT SVT = DstVT.getVectorElementType();
19046     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19047     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19048                                    MVT::v2f64, N->getOperand(0));
19049     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19050
19051     if (ExperimentalVectorWideningLegalization) {
19052       // If we are legalizing vectors by widening, we already have the desired
19053       // legal vector type, just return it.
19054       Results.push_back(ToVecInt);
19055       return;
19056     }
19057
19058     SmallVector<SDValue, 8> Elts;
19059     for (unsigned i = 0, e = NumElts; i != e; ++i)
19060       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19061                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19062
19063     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19064   }
19065   }
19066 }
19067
19068 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19069   switch ((X86ISD::NodeType)Opcode) {
19070   case X86ISD::FIRST_NUMBER:       break;
19071   case X86ISD::BSF:                return "X86ISD::BSF";
19072   case X86ISD::BSR:                return "X86ISD::BSR";
19073   case X86ISD::SHLD:               return "X86ISD::SHLD";
19074   case X86ISD::SHRD:               return "X86ISD::SHRD";
19075   case X86ISD::FAND:               return "X86ISD::FAND";
19076   case X86ISD::FANDN:              return "X86ISD::FANDN";
19077   case X86ISD::FOR:                return "X86ISD::FOR";
19078   case X86ISD::FXOR:               return "X86ISD::FXOR";
19079   case X86ISD::FILD:               return "X86ISD::FILD";
19080   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19081   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19082   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19083   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19084   case X86ISD::FLD:                return "X86ISD::FLD";
19085   case X86ISD::FST:                return "X86ISD::FST";
19086   case X86ISD::CALL:               return "X86ISD::CALL";
19087   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19088   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19089   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19090   case X86ISD::BT:                 return "X86ISD::BT";
19091   case X86ISD::CMP:                return "X86ISD::CMP";
19092   case X86ISD::COMI:               return "X86ISD::COMI";
19093   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19094   case X86ISD::CMPM:               return "X86ISD::CMPM";
19095   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19096   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19097   case X86ISD::SETCC:              return "X86ISD::SETCC";
19098   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19099   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19100   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19101   case X86ISD::CMOV:               return "X86ISD::CMOV";
19102   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19103   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19104   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19105   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19106   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19107   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19108   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19109   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19110   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19111   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19112   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19113   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19114   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19115   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19116   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19117   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19118   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19119   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19120   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19121   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19122   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19123   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19124   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19125   case X86ISD::HADD:               return "X86ISD::HADD";
19126   case X86ISD::HSUB:               return "X86ISD::HSUB";
19127   case X86ISD::FHADD:              return "X86ISD::FHADD";
19128   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19129   case X86ISD::ABS:                return "X86ISD::ABS";
19130   case X86ISD::FMAX:               return "X86ISD::FMAX";
19131   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19132   case X86ISD::FMIN:               return "X86ISD::FMIN";
19133   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19134   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19135   case X86ISD::FMINC:              return "X86ISD::FMINC";
19136   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19137   case X86ISD::FRCP:               return "X86ISD::FRCP";
19138   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19139   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19140   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19141   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19142   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19143   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19144   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19145   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19146   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19147   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19148   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19149   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19150   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19151   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19152   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19153   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19154   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19155   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19156   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19157   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19158   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19159   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19160   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19161   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19162   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19163   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19164   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19165   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19166   case X86ISD::VSHL:               return "X86ISD::VSHL";
19167   case X86ISD::VSRL:               return "X86ISD::VSRL";
19168   case X86ISD::VSRA:               return "X86ISD::VSRA";
19169   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19170   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19171   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19172   case X86ISD::CMPP:               return "X86ISD::CMPP";
19173   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19174   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19175   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19176   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19177   case X86ISD::ADD:                return "X86ISD::ADD";
19178   case X86ISD::SUB:                return "X86ISD::SUB";
19179   case X86ISD::ADC:                return "X86ISD::ADC";
19180   case X86ISD::SBB:                return "X86ISD::SBB";
19181   case X86ISD::SMUL:               return "X86ISD::SMUL";
19182   case X86ISD::UMUL:               return "X86ISD::UMUL";
19183   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19184   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19185   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19186   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19187   case X86ISD::INC:                return "X86ISD::INC";
19188   case X86ISD::DEC:                return "X86ISD::DEC";
19189   case X86ISD::OR:                 return "X86ISD::OR";
19190   case X86ISD::XOR:                return "X86ISD::XOR";
19191   case X86ISD::AND:                return "X86ISD::AND";
19192   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19193   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19194   case X86ISD::PTEST:              return "X86ISD::PTEST";
19195   case X86ISD::TESTP:              return "X86ISD::TESTP";
19196   case X86ISD::TESTM:              return "X86ISD::TESTM";
19197   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19198   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19199   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19200   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19201   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19202   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19203   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19204   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19205   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19206   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19207   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19208   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19209   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19210   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19211   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19212   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19213   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19214   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19215   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19216   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19217   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19218   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19219   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19220   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19221   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19222   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19223   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19224   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19225   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19226   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19227   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19228   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19229   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19230   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19231   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19232   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19233   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19234   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19235   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19236   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19237   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19238   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19239   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19240   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19241   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19242   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19243   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19244   case X86ISD::SAHF:               return "X86ISD::SAHF";
19245   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19246   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19247   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19248   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19249   case X86ISD::FMADD:              return "X86ISD::FMADD";
19250   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19251   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19252   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19253   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19254   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19255   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19256   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19257   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19258   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19259   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19260   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19261   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19262   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19263   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19264   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19265   case X86ISD::XTEST:              return "X86ISD::XTEST";
19266   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19267   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19268   case X86ISD::SELECT:             return "X86ISD::SELECT";
19269   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19270   case X86ISD::RCP28:              return "X86ISD::RCP28";
19271   case X86ISD::EXP2:               return "X86ISD::EXP2";
19272   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19273   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19274   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19275   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19276   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19277   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19278   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19279   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19280   case X86ISD::ADDS:               return "X86ISD::ADDS";
19281   case X86ISD::SUBS:               return "X86ISD::SUBS";
19282   case X86ISD::AVG:                return "X86ISD::AVG";
19283   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19284   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19285   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19286   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19287   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19288   }
19289   return nullptr;
19290 }
19291
19292 // isLegalAddressingMode - Return true if the addressing mode represented
19293 // by AM is legal for this target, for a load/store of the specified type.
19294 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19295                                               const AddrMode &AM, Type *Ty,
19296                                               unsigned AS) const {
19297   // X86 supports extremely general addressing modes.
19298   CodeModel::Model M = getTargetMachine().getCodeModel();
19299   Reloc::Model R = getTargetMachine().getRelocationModel();
19300
19301   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19302   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19303     return false;
19304
19305   if (AM.BaseGV) {
19306     unsigned GVFlags =
19307       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19308
19309     // If a reference to this global requires an extra load, we can't fold it.
19310     if (isGlobalStubReference(GVFlags))
19311       return false;
19312
19313     // If BaseGV requires a register for the PIC base, we cannot also have a
19314     // BaseReg specified.
19315     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19316       return false;
19317
19318     // If lower 4G is not available, then we must use rip-relative addressing.
19319     if ((M != CodeModel::Small || R != Reloc::Static) &&
19320         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19321       return false;
19322   }
19323
19324   switch (AM.Scale) {
19325   case 0:
19326   case 1:
19327   case 2:
19328   case 4:
19329   case 8:
19330     // These scales always work.
19331     break;
19332   case 3:
19333   case 5:
19334   case 9:
19335     // These scales are formed with basereg+scalereg.  Only accept if there is
19336     // no basereg yet.
19337     if (AM.HasBaseReg)
19338       return false;
19339     break;
19340   default:  // Other stuff never works.
19341     return false;
19342   }
19343
19344   return true;
19345 }
19346
19347 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19348   unsigned Bits = Ty->getScalarSizeInBits();
19349
19350   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19351   // particularly cheaper than those without.
19352   if (Bits == 8)
19353     return false;
19354
19355   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19356   // variable shifts just as cheap as scalar ones.
19357   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19358     return false;
19359
19360   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19361   // fully general vector.
19362   return true;
19363 }
19364
19365 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19366   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19367     return false;
19368   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19369   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19370   return NumBits1 > NumBits2;
19371 }
19372
19373 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19374   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19375     return false;
19376
19377   if (!isTypeLegal(EVT::getEVT(Ty1)))
19378     return false;
19379
19380   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19381
19382   // Assuming the caller doesn't have a zeroext or signext return parameter,
19383   // truncation all the way down to i1 is valid.
19384   return true;
19385 }
19386
19387 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19388   return isInt<32>(Imm);
19389 }
19390
19391 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19392   // Can also use sub to handle negated immediates.
19393   return isInt<32>(Imm);
19394 }
19395
19396 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19397   if (!VT1.isInteger() || !VT2.isInteger())
19398     return false;
19399   unsigned NumBits1 = VT1.getSizeInBits();
19400   unsigned NumBits2 = VT2.getSizeInBits();
19401   return NumBits1 > NumBits2;
19402 }
19403
19404 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19405   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19406   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19407 }
19408
19409 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19410   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19411   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19412 }
19413
19414 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19415   EVT VT1 = Val.getValueType();
19416   if (isZExtFree(VT1, VT2))
19417     return true;
19418
19419   if (Val.getOpcode() != ISD::LOAD)
19420     return false;
19421
19422   if (!VT1.isSimple() || !VT1.isInteger() ||
19423       !VT2.isSimple() || !VT2.isInteger())
19424     return false;
19425
19426   switch (VT1.getSimpleVT().SimpleTy) {
19427   default: break;
19428   case MVT::i8:
19429   case MVT::i16:
19430   case MVT::i32:
19431     // X86 has 8, 16, and 32-bit zero-extending loads.
19432     return true;
19433   }
19434
19435   return false;
19436 }
19437
19438 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19439
19440 bool
19441 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19442   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19443     return false;
19444
19445   VT = VT.getScalarType();
19446
19447   if (!VT.isSimple())
19448     return false;
19449
19450   switch (VT.getSimpleVT().SimpleTy) {
19451   case MVT::f32:
19452   case MVT::f64:
19453     return true;
19454   default:
19455     break;
19456   }
19457
19458   return false;
19459 }
19460
19461 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19462   // i16 instructions are longer (0x66 prefix) and potentially slower.
19463   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19464 }
19465
19466 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19467 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19468 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19469 /// are assumed to be legal.
19470 bool
19471 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19472                                       EVT VT) const {
19473   if (!VT.isSimple())
19474     return false;
19475
19476   // Not for i1 vectors
19477   if (VT.getScalarType() == MVT::i1)
19478     return false;
19479
19480   // Very little shuffling can be done for 64-bit vectors right now.
19481   if (VT.getSizeInBits() == 64)
19482     return false;
19483
19484   // We only care that the types being shuffled are legal. The lowering can
19485   // handle any possible shuffle mask that results.
19486   return isTypeLegal(VT.getSimpleVT());
19487 }
19488
19489 bool
19490 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19491                                           EVT VT) const {
19492   // Just delegate to the generic legality, clear masks aren't special.
19493   return isShuffleMaskLegal(Mask, VT);
19494 }
19495
19496 //===----------------------------------------------------------------------===//
19497 //                           X86 Scheduler Hooks
19498 //===----------------------------------------------------------------------===//
19499
19500 /// Utility function to emit xbegin specifying the start of an RTM region.
19501 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19502                                      const TargetInstrInfo *TII) {
19503   DebugLoc DL = MI->getDebugLoc();
19504
19505   const BasicBlock *BB = MBB->getBasicBlock();
19506   MachineFunction::iterator I = MBB;
19507   ++I;
19508
19509   // For the v = xbegin(), we generate
19510   //
19511   // thisMBB:
19512   //  xbegin sinkMBB
19513   //
19514   // mainMBB:
19515   //  eax = -1
19516   //
19517   // sinkMBB:
19518   //  v = eax
19519
19520   MachineBasicBlock *thisMBB = MBB;
19521   MachineFunction *MF = MBB->getParent();
19522   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19523   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19524   MF->insert(I, mainMBB);
19525   MF->insert(I, sinkMBB);
19526
19527   // Transfer the remainder of BB and its successor edges to sinkMBB.
19528   sinkMBB->splice(sinkMBB->begin(), MBB,
19529                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19530   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19531
19532   // thisMBB:
19533   //  xbegin sinkMBB
19534   //  # fallthrough to mainMBB
19535   //  # abortion to sinkMBB
19536   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19537   thisMBB->addSuccessor(mainMBB);
19538   thisMBB->addSuccessor(sinkMBB);
19539
19540   // mainMBB:
19541   //  EAX = -1
19542   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19543   mainMBB->addSuccessor(sinkMBB);
19544
19545   // sinkMBB:
19546   // EAX is live into the sinkMBB
19547   sinkMBB->addLiveIn(X86::EAX);
19548   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19549           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19550     .addReg(X86::EAX);
19551
19552   MI->eraseFromParent();
19553   return sinkMBB;
19554 }
19555
19556 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19557 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19558 // in the .td file.
19559 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19560                                        const TargetInstrInfo *TII) {
19561   unsigned Opc;
19562   switch (MI->getOpcode()) {
19563   default: llvm_unreachable("illegal opcode!");
19564   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19565   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19566   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19567   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19568   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19569   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19570   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19571   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19572   }
19573
19574   DebugLoc dl = MI->getDebugLoc();
19575   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19576
19577   unsigned NumArgs = MI->getNumOperands();
19578   for (unsigned i = 1; i < NumArgs; ++i) {
19579     MachineOperand &Op = MI->getOperand(i);
19580     if (!(Op.isReg() && Op.isImplicit()))
19581       MIB.addOperand(Op);
19582   }
19583   if (MI->hasOneMemOperand())
19584     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19585
19586   BuildMI(*BB, MI, dl,
19587     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19588     .addReg(X86::XMM0);
19589
19590   MI->eraseFromParent();
19591   return BB;
19592 }
19593
19594 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19595 // defs in an instruction pattern
19596 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19597                                        const TargetInstrInfo *TII) {
19598   unsigned Opc;
19599   switch (MI->getOpcode()) {
19600   default: llvm_unreachable("illegal opcode!");
19601   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19602   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19603   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19604   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19605   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19606   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19607   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19608   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19609   }
19610
19611   DebugLoc dl = MI->getDebugLoc();
19612   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19613
19614   unsigned NumArgs = MI->getNumOperands(); // remove the results
19615   for (unsigned i = 1; i < NumArgs; ++i) {
19616     MachineOperand &Op = MI->getOperand(i);
19617     if (!(Op.isReg() && Op.isImplicit()))
19618       MIB.addOperand(Op);
19619   }
19620   if (MI->hasOneMemOperand())
19621     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19622
19623   BuildMI(*BB, MI, dl,
19624     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19625     .addReg(X86::ECX);
19626
19627   MI->eraseFromParent();
19628   return BB;
19629 }
19630
19631 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19632                                       const X86Subtarget *Subtarget) {
19633   DebugLoc dl = MI->getDebugLoc();
19634   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19635   // Address into RAX/EAX, other two args into ECX, EDX.
19636   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19637   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19638   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19639   for (int i = 0; i < X86::AddrNumOperands; ++i)
19640     MIB.addOperand(MI->getOperand(i));
19641
19642   unsigned ValOps = X86::AddrNumOperands;
19643   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19644     .addReg(MI->getOperand(ValOps).getReg());
19645   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19646     .addReg(MI->getOperand(ValOps+1).getReg());
19647
19648   // The instruction doesn't actually take any operands though.
19649   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19650
19651   MI->eraseFromParent(); // The pseudo is gone now.
19652   return BB;
19653 }
19654
19655 MachineBasicBlock *
19656 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19657                                                  MachineBasicBlock *MBB) const {
19658   // Emit va_arg instruction on X86-64.
19659
19660   // Operands to this pseudo-instruction:
19661   // 0  ) Output        : destination address (reg)
19662   // 1-5) Input         : va_list address (addr, i64mem)
19663   // 6  ) ArgSize       : Size (in bytes) of vararg type
19664   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19665   // 8  ) Align         : Alignment of type
19666   // 9  ) EFLAGS (implicit-def)
19667
19668   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19669   static_assert(X86::AddrNumOperands == 5,
19670                 "VAARG_64 assumes 5 address operands");
19671
19672   unsigned DestReg = MI->getOperand(0).getReg();
19673   MachineOperand &Base = MI->getOperand(1);
19674   MachineOperand &Scale = MI->getOperand(2);
19675   MachineOperand &Index = MI->getOperand(3);
19676   MachineOperand &Disp = MI->getOperand(4);
19677   MachineOperand &Segment = MI->getOperand(5);
19678   unsigned ArgSize = MI->getOperand(6).getImm();
19679   unsigned ArgMode = MI->getOperand(7).getImm();
19680   unsigned Align = MI->getOperand(8).getImm();
19681
19682   // Memory Reference
19683   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19684   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19685   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19686
19687   // Machine Information
19688   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19689   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19690   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19691   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19692   DebugLoc DL = MI->getDebugLoc();
19693
19694   // struct va_list {
19695   //   i32   gp_offset
19696   //   i32   fp_offset
19697   //   i64   overflow_area (address)
19698   //   i64   reg_save_area (address)
19699   // }
19700   // sizeof(va_list) = 24
19701   // alignment(va_list) = 8
19702
19703   unsigned TotalNumIntRegs = 6;
19704   unsigned TotalNumXMMRegs = 8;
19705   bool UseGPOffset = (ArgMode == 1);
19706   bool UseFPOffset = (ArgMode == 2);
19707   unsigned MaxOffset = TotalNumIntRegs * 8 +
19708                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19709
19710   /* Align ArgSize to a multiple of 8 */
19711   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19712   bool NeedsAlign = (Align > 8);
19713
19714   MachineBasicBlock *thisMBB = MBB;
19715   MachineBasicBlock *overflowMBB;
19716   MachineBasicBlock *offsetMBB;
19717   MachineBasicBlock *endMBB;
19718
19719   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19720   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19721   unsigned OffsetReg = 0;
19722
19723   if (!UseGPOffset && !UseFPOffset) {
19724     // If we only pull from the overflow region, we don't create a branch.
19725     // We don't need to alter control flow.
19726     OffsetDestReg = 0; // unused
19727     OverflowDestReg = DestReg;
19728
19729     offsetMBB = nullptr;
19730     overflowMBB = thisMBB;
19731     endMBB = thisMBB;
19732   } else {
19733     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19734     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19735     // If not, pull from overflow_area. (branch to overflowMBB)
19736     //
19737     //       thisMBB
19738     //         |     .
19739     //         |        .
19740     //     offsetMBB   overflowMBB
19741     //         |        .
19742     //         |     .
19743     //        endMBB
19744
19745     // Registers for the PHI in endMBB
19746     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19747     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19748
19749     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19750     MachineFunction *MF = MBB->getParent();
19751     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19752     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19753     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19754
19755     MachineFunction::iterator MBBIter = MBB;
19756     ++MBBIter;
19757
19758     // Insert the new basic blocks
19759     MF->insert(MBBIter, offsetMBB);
19760     MF->insert(MBBIter, overflowMBB);
19761     MF->insert(MBBIter, endMBB);
19762
19763     // Transfer the remainder of MBB and its successor edges to endMBB.
19764     endMBB->splice(endMBB->begin(), thisMBB,
19765                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19766     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19767
19768     // Make offsetMBB and overflowMBB successors of thisMBB
19769     thisMBB->addSuccessor(offsetMBB);
19770     thisMBB->addSuccessor(overflowMBB);
19771
19772     // endMBB is a successor of both offsetMBB and overflowMBB
19773     offsetMBB->addSuccessor(endMBB);
19774     overflowMBB->addSuccessor(endMBB);
19775
19776     // Load the offset value into a register
19777     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19778     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19779       .addOperand(Base)
19780       .addOperand(Scale)
19781       .addOperand(Index)
19782       .addDisp(Disp, UseFPOffset ? 4 : 0)
19783       .addOperand(Segment)
19784       .setMemRefs(MMOBegin, MMOEnd);
19785
19786     // Check if there is enough room left to pull this argument.
19787     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19788       .addReg(OffsetReg)
19789       .addImm(MaxOffset + 8 - ArgSizeA8);
19790
19791     // Branch to "overflowMBB" if offset >= max
19792     // Fall through to "offsetMBB" otherwise
19793     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19794       .addMBB(overflowMBB);
19795   }
19796
19797   // In offsetMBB, emit code to use the reg_save_area.
19798   if (offsetMBB) {
19799     assert(OffsetReg != 0);
19800
19801     // Read the reg_save_area address.
19802     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19803     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19804       .addOperand(Base)
19805       .addOperand(Scale)
19806       .addOperand(Index)
19807       .addDisp(Disp, 16)
19808       .addOperand(Segment)
19809       .setMemRefs(MMOBegin, MMOEnd);
19810
19811     // Zero-extend the offset
19812     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19813       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19814         .addImm(0)
19815         .addReg(OffsetReg)
19816         .addImm(X86::sub_32bit);
19817
19818     // Add the offset to the reg_save_area to get the final address.
19819     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19820       .addReg(OffsetReg64)
19821       .addReg(RegSaveReg);
19822
19823     // Compute the offset for the next argument
19824     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19825     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19826       .addReg(OffsetReg)
19827       .addImm(UseFPOffset ? 16 : 8);
19828
19829     // Store it back into the va_list.
19830     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19831       .addOperand(Base)
19832       .addOperand(Scale)
19833       .addOperand(Index)
19834       .addDisp(Disp, UseFPOffset ? 4 : 0)
19835       .addOperand(Segment)
19836       .addReg(NextOffsetReg)
19837       .setMemRefs(MMOBegin, MMOEnd);
19838
19839     // Jump to endMBB
19840     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19841       .addMBB(endMBB);
19842   }
19843
19844   //
19845   // Emit code to use overflow area
19846   //
19847
19848   // Load the overflow_area address into a register.
19849   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19850   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19851     .addOperand(Base)
19852     .addOperand(Scale)
19853     .addOperand(Index)
19854     .addDisp(Disp, 8)
19855     .addOperand(Segment)
19856     .setMemRefs(MMOBegin, MMOEnd);
19857
19858   // If we need to align it, do so. Otherwise, just copy the address
19859   // to OverflowDestReg.
19860   if (NeedsAlign) {
19861     // Align the overflow address
19862     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19863     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19864
19865     // aligned_addr = (addr + (align-1)) & ~(align-1)
19866     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19867       .addReg(OverflowAddrReg)
19868       .addImm(Align-1);
19869
19870     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19871       .addReg(TmpReg)
19872       .addImm(~(uint64_t)(Align-1));
19873   } else {
19874     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19875       .addReg(OverflowAddrReg);
19876   }
19877
19878   // Compute the next overflow address after this argument.
19879   // (the overflow address should be kept 8-byte aligned)
19880   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19881   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19882     .addReg(OverflowDestReg)
19883     .addImm(ArgSizeA8);
19884
19885   // Store the new overflow address.
19886   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19887     .addOperand(Base)
19888     .addOperand(Scale)
19889     .addOperand(Index)
19890     .addDisp(Disp, 8)
19891     .addOperand(Segment)
19892     .addReg(NextAddrReg)
19893     .setMemRefs(MMOBegin, MMOEnd);
19894
19895   // If we branched, emit the PHI to the front of endMBB.
19896   if (offsetMBB) {
19897     BuildMI(*endMBB, endMBB->begin(), DL,
19898             TII->get(X86::PHI), DestReg)
19899       .addReg(OffsetDestReg).addMBB(offsetMBB)
19900       .addReg(OverflowDestReg).addMBB(overflowMBB);
19901   }
19902
19903   // Erase the pseudo instruction
19904   MI->eraseFromParent();
19905
19906   return endMBB;
19907 }
19908
19909 MachineBasicBlock *
19910 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19911                                                  MachineInstr *MI,
19912                                                  MachineBasicBlock *MBB) const {
19913   // Emit code to save XMM registers to the stack. The ABI says that the
19914   // number of registers to save is given in %al, so it's theoretically
19915   // possible to do an indirect jump trick to avoid saving all of them,
19916   // however this code takes a simpler approach and just executes all
19917   // of the stores if %al is non-zero. It's less code, and it's probably
19918   // easier on the hardware branch predictor, and stores aren't all that
19919   // expensive anyway.
19920
19921   // Create the new basic blocks. One block contains all the XMM stores,
19922   // and one block is the final destination regardless of whether any
19923   // stores were performed.
19924   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19925   MachineFunction *F = MBB->getParent();
19926   MachineFunction::iterator MBBIter = MBB;
19927   ++MBBIter;
19928   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19929   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19930   F->insert(MBBIter, XMMSaveMBB);
19931   F->insert(MBBIter, EndMBB);
19932
19933   // Transfer the remainder of MBB and its successor edges to EndMBB.
19934   EndMBB->splice(EndMBB->begin(), MBB,
19935                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19936   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19937
19938   // The original block will now fall through to the XMM save block.
19939   MBB->addSuccessor(XMMSaveMBB);
19940   // The XMMSaveMBB will fall through to the end block.
19941   XMMSaveMBB->addSuccessor(EndMBB);
19942
19943   // Now add the instructions.
19944   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19945   DebugLoc DL = MI->getDebugLoc();
19946
19947   unsigned CountReg = MI->getOperand(0).getReg();
19948   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19949   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19950
19951   if (!Subtarget->isTargetWin64()) {
19952     // If %al is 0, branch around the XMM save block.
19953     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19954     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19955     MBB->addSuccessor(EndMBB);
19956   }
19957
19958   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19959   // that was just emitted, but clearly shouldn't be "saved".
19960   assert((MI->getNumOperands() <= 3 ||
19961           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19962           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19963          && "Expected last argument to be EFLAGS");
19964   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19965   // In the XMM save block, save all the XMM argument registers.
19966   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19967     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19968     MachineMemOperand *MMO = F->getMachineMemOperand(
19969         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
19970         MachineMemOperand::MOStore,
19971         /*Size=*/16, /*Align=*/16);
19972     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19973       .addFrameIndex(RegSaveFrameIndex)
19974       .addImm(/*Scale=*/1)
19975       .addReg(/*IndexReg=*/0)
19976       .addImm(/*Disp=*/Offset)
19977       .addReg(/*Segment=*/0)
19978       .addReg(MI->getOperand(i).getReg())
19979       .addMemOperand(MMO);
19980   }
19981
19982   MI->eraseFromParent();   // The pseudo instruction is gone now.
19983
19984   return EndMBB;
19985 }
19986
19987 // The EFLAGS operand of SelectItr might be missing a kill marker
19988 // because there were multiple uses of EFLAGS, and ISel didn't know
19989 // which to mark. Figure out whether SelectItr should have had a
19990 // kill marker, and set it if it should. Returns the correct kill
19991 // marker value.
19992 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19993                                      MachineBasicBlock* BB,
19994                                      const TargetRegisterInfo* TRI) {
19995   // Scan forward through BB for a use/def of EFLAGS.
19996   MachineBasicBlock::iterator miI(std::next(SelectItr));
19997   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19998     const MachineInstr& mi = *miI;
19999     if (mi.readsRegister(X86::EFLAGS))
20000       return false;
20001     if (mi.definesRegister(X86::EFLAGS))
20002       break; // Should have kill-flag - update below.
20003   }
20004
20005   // If we hit the end of the block, check whether EFLAGS is live into a
20006   // successor.
20007   if (miI == BB->end()) {
20008     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20009                                           sEnd = BB->succ_end();
20010          sItr != sEnd; ++sItr) {
20011       MachineBasicBlock* succ = *sItr;
20012       if (succ->isLiveIn(X86::EFLAGS))
20013         return false;
20014     }
20015   }
20016
20017   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20018   // out. SelectMI should have a kill flag on EFLAGS.
20019   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20020   return true;
20021 }
20022
20023 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20024 // together with other CMOV pseudo-opcodes into a single basic-block with
20025 // conditional jump around it.
20026 static bool isCMOVPseudo(MachineInstr *MI) {
20027   switch (MI->getOpcode()) {
20028   case X86::CMOV_FR32:
20029   case X86::CMOV_FR64:
20030   case X86::CMOV_GR8:
20031   case X86::CMOV_GR16:
20032   case X86::CMOV_GR32:
20033   case X86::CMOV_RFP32:
20034   case X86::CMOV_RFP64:
20035   case X86::CMOV_RFP80:
20036   case X86::CMOV_V2F64:
20037   case X86::CMOV_V2I64:
20038   case X86::CMOV_V4F32:
20039   case X86::CMOV_V4F64:
20040   case X86::CMOV_V4I64:
20041   case X86::CMOV_V16F32:
20042   case X86::CMOV_V8F32:
20043   case X86::CMOV_V8F64:
20044   case X86::CMOV_V8I64:
20045   case X86::CMOV_V8I1:
20046   case X86::CMOV_V16I1:
20047   case X86::CMOV_V32I1:
20048   case X86::CMOV_V64I1:
20049     return true;
20050
20051   default:
20052     return false;
20053   }
20054 }
20055
20056 MachineBasicBlock *
20057 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20058                                      MachineBasicBlock *BB) const {
20059   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20060   DebugLoc DL = MI->getDebugLoc();
20061
20062   // To "insert" a SELECT_CC instruction, we actually have to insert the
20063   // diamond control-flow pattern.  The incoming instruction knows the
20064   // destination vreg to set, the condition code register to branch on, the
20065   // true/false values to select between, and a branch opcode to use.
20066   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20067   MachineFunction::iterator It = BB;
20068   ++It;
20069
20070   //  thisMBB:
20071   //  ...
20072   //   TrueVal = ...
20073   //   cmpTY ccX, r1, r2
20074   //   bCC copy1MBB
20075   //   fallthrough --> copy0MBB
20076   MachineBasicBlock *thisMBB = BB;
20077   MachineFunction *F = BB->getParent();
20078
20079   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20080   // as described above, by inserting a BB, and then making a PHI at the join
20081   // point to select the true and false operands of the CMOV in the PHI.
20082   //
20083   // The code also handles two different cases of multiple CMOV opcodes
20084   // in a row.
20085   //
20086   // Case 1:
20087   // In this case, there are multiple CMOVs in a row, all which are based on
20088   // the same condition setting (or the exact opposite condition setting).
20089   // In this case we can lower all the CMOVs using a single inserted BB, and
20090   // then make a number of PHIs at the join point to model the CMOVs. The only
20091   // trickiness here, is that in a case like:
20092   //
20093   // t2 = CMOV cond1 t1, f1
20094   // t3 = CMOV cond1 t2, f2
20095   //
20096   // when rewriting this into PHIs, we have to perform some renaming on the
20097   // temps since you cannot have a PHI operand refer to a PHI result earlier
20098   // in the same block.  The "simple" but wrong lowering would be:
20099   //
20100   // t2 = PHI t1(BB1), f1(BB2)
20101   // t3 = PHI t2(BB1), f2(BB2)
20102   //
20103   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20104   // renaming is to note that on the path through BB1, t2 is really just a
20105   // copy of t1, and do that renaming, properly generating:
20106   //
20107   // t2 = PHI t1(BB1), f1(BB2)
20108   // t3 = PHI t1(BB1), f2(BB2)
20109   //
20110   // Case 2, we lower cascaded CMOVs such as
20111   //
20112   //   (CMOV (CMOV F, T, cc1), T, cc2)
20113   //
20114   // to two successives branches.  For that, we look for another CMOV as the
20115   // following instruction.
20116   //
20117   // Without this, we would add a PHI between the two jumps, which ends up
20118   // creating a few copies all around. For instance, for
20119   //
20120   //    (sitofp (zext (fcmp une)))
20121   //
20122   // we would generate:
20123   //
20124   //         ucomiss %xmm1, %xmm0
20125   //         movss  <1.0f>, %xmm0
20126   //         movaps  %xmm0, %xmm1
20127   //         jne     .LBB5_2
20128   //         xorps   %xmm1, %xmm1
20129   // .LBB5_2:
20130   //         jp      .LBB5_4
20131   //         movaps  %xmm1, %xmm0
20132   // .LBB5_4:
20133   //         retq
20134   //
20135   // because this custom-inserter would have generated:
20136   //
20137   //   A
20138   //   | \
20139   //   |  B
20140   //   | /
20141   //   C
20142   //   | \
20143   //   |  D
20144   //   | /
20145   //   E
20146   //
20147   // A: X = ...; Y = ...
20148   // B: empty
20149   // C: Z = PHI [X, A], [Y, B]
20150   // D: empty
20151   // E: PHI [X, C], [Z, D]
20152   //
20153   // If we lower both CMOVs in a single step, we can instead generate:
20154   //
20155   //   A
20156   //   | \
20157   //   |  C
20158   //   | /|
20159   //   |/ |
20160   //   |  |
20161   //   |  D
20162   //   | /
20163   //   E
20164   //
20165   // A: X = ...; Y = ...
20166   // D: empty
20167   // E: PHI [X, A], [X, C], [Y, D]
20168   //
20169   // Which, in our sitofp/fcmp example, gives us something like:
20170   //
20171   //         ucomiss %xmm1, %xmm0
20172   //         movss  <1.0f>, %xmm0
20173   //         jne     .LBB5_4
20174   //         jp      .LBB5_4
20175   //         xorps   %xmm0, %xmm0
20176   // .LBB5_4:
20177   //         retq
20178   //
20179   MachineInstr *CascadedCMOV = nullptr;
20180   MachineInstr *LastCMOV = MI;
20181   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20182   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20183   MachineBasicBlock::iterator NextMIIt =
20184       std::next(MachineBasicBlock::iterator(MI));
20185
20186   // Check for case 1, where there are multiple CMOVs with the same condition
20187   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20188   // number of jumps the most.
20189
20190   if (isCMOVPseudo(MI)) {
20191     // See if we have a string of CMOVS with the same condition.
20192     while (NextMIIt != BB->end() &&
20193            isCMOVPseudo(NextMIIt) &&
20194            (NextMIIt->getOperand(3).getImm() == CC ||
20195             NextMIIt->getOperand(3).getImm() == OppCC)) {
20196       LastCMOV = &*NextMIIt;
20197       ++NextMIIt;
20198     }
20199   }
20200
20201   // This checks for case 2, but only do this if we didn't already find
20202   // case 1, as indicated by LastCMOV == MI.
20203   if (LastCMOV == MI &&
20204       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20205       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20206       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20207     CascadedCMOV = &*NextMIIt;
20208   }
20209
20210   MachineBasicBlock *jcc1MBB = nullptr;
20211
20212   // If we have a cascaded CMOV, we lower it to two successive branches to
20213   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20214   if (CascadedCMOV) {
20215     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20216     F->insert(It, jcc1MBB);
20217     jcc1MBB->addLiveIn(X86::EFLAGS);
20218   }
20219
20220   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20221   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20222   F->insert(It, copy0MBB);
20223   F->insert(It, sinkMBB);
20224
20225   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20226   // live into the sink and copy blocks.
20227   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20228
20229   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20230   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20231       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20232     copy0MBB->addLiveIn(X86::EFLAGS);
20233     sinkMBB->addLiveIn(X86::EFLAGS);
20234   }
20235
20236   // Transfer the remainder of BB and its successor edges to sinkMBB.
20237   sinkMBB->splice(sinkMBB->begin(), BB,
20238                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20239   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20240
20241   // Add the true and fallthrough blocks as its successors.
20242   if (CascadedCMOV) {
20243     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20244     BB->addSuccessor(jcc1MBB);
20245
20246     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20247     // jump to the sinkMBB.
20248     jcc1MBB->addSuccessor(copy0MBB);
20249     jcc1MBB->addSuccessor(sinkMBB);
20250   } else {
20251     BB->addSuccessor(copy0MBB);
20252   }
20253
20254   // The true block target of the first (or only) branch is always sinkMBB.
20255   BB->addSuccessor(sinkMBB);
20256
20257   // Create the conditional branch instruction.
20258   unsigned Opc = X86::GetCondBranchFromCond(CC);
20259   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20260
20261   if (CascadedCMOV) {
20262     unsigned Opc2 = X86::GetCondBranchFromCond(
20263         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20264     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20265   }
20266
20267   //  copy0MBB:
20268   //   %FalseValue = ...
20269   //   # fallthrough to sinkMBB
20270   copy0MBB->addSuccessor(sinkMBB);
20271
20272   //  sinkMBB:
20273   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20274   //  ...
20275   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20276   MachineBasicBlock::iterator MIItEnd =
20277     std::next(MachineBasicBlock::iterator(LastCMOV));
20278   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20279   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20280   MachineInstrBuilder MIB;
20281
20282   // As we are creating the PHIs, we have to be careful if there is more than
20283   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20284   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20285   // That also means that PHI construction must work forward from earlier to
20286   // later, and that the code must maintain a mapping from earlier PHI's
20287   // destination registers, and the registers that went into the PHI.
20288
20289   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20290     unsigned DestReg = MIIt->getOperand(0).getReg();
20291     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20292     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20293
20294     // If this CMOV we are generating is the opposite condition from
20295     // the jump we generated, then we have to swap the operands for the
20296     // PHI that is going to be generated.
20297     if (MIIt->getOperand(3).getImm() == OppCC)
20298         std::swap(Op1Reg, Op2Reg);
20299
20300     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20301       Op1Reg = RegRewriteTable[Op1Reg].first;
20302
20303     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20304       Op2Reg = RegRewriteTable[Op2Reg].second;
20305
20306     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20307                   TII->get(X86::PHI), DestReg)
20308           .addReg(Op1Reg).addMBB(copy0MBB)
20309           .addReg(Op2Reg).addMBB(thisMBB);
20310
20311     // Add this PHI to the rewrite table.
20312     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20313   }
20314
20315   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20316   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20317   if (CascadedCMOV) {
20318     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20319     // Copy the PHI result to the register defined by the second CMOV.
20320     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20321             DL, TII->get(TargetOpcode::COPY),
20322             CascadedCMOV->getOperand(0).getReg())
20323         .addReg(MI->getOperand(0).getReg());
20324     CascadedCMOV->eraseFromParent();
20325   }
20326
20327   // Now remove the CMOV(s).
20328   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20329     (MIIt++)->eraseFromParent();
20330
20331   return sinkMBB;
20332 }
20333
20334 MachineBasicBlock *
20335 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20336                                        MachineBasicBlock *BB) const {
20337   // Combine the following atomic floating-point modification pattern:
20338   //   a.store(reg OP a.load(acquire), release)
20339   // Transform them into:
20340   //   OPss (%gpr), %xmm
20341   //   movss %xmm, (%gpr)
20342   // Or sd equivalent for 64-bit operations.
20343   unsigned MOp, FOp;
20344   switch (MI->getOpcode()) {
20345   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20346   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20347   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20348   }
20349   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20350   DebugLoc DL = MI->getDebugLoc();
20351   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20352   unsigned MSrc = MI->getOperand(0).getReg();
20353   unsigned VSrc = MI->getOperand(5).getReg();
20354   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20355                                 .addReg(/*Base=*/MSrc)
20356                                 .addImm(/*Scale=*/1)
20357                                 .addReg(/*Index=*/0)
20358                                 .addImm(0)
20359                                 .addReg(0);
20360   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20361                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20362                           .addReg(VSrc)
20363                           .addReg(/*Base=*/MSrc)
20364                           .addImm(/*Scale=*/1)
20365                           .addReg(/*Index=*/0)
20366                           .addImm(/*Disp=*/0)
20367                           .addReg(/*Segment=*/0);
20368   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20369   MI->eraseFromParent(); // The pseudo instruction is gone now.
20370   return BB;
20371 }
20372
20373 MachineBasicBlock *
20374 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20375                                         MachineBasicBlock *BB) const {
20376   MachineFunction *MF = BB->getParent();
20377   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20378   DebugLoc DL = MI->getDebugLoc();
20379   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20380
20381   assert(MF->shouldSplitStack());
20382
20383   const bool Is64Bit = Subtarget->is64Bit();
20384   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20385
20386   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20387   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20388
20389   // BB:
20390   //  ... [Till the alloca]
20391   // If stacklet is not large enough, jump to mallocMBB
20392   //
20393   // bumpMBB:
20394   //  Allocate by subtracting from RSP
20395   //  Jump to continueMBB
20396   //
20397   // mallocMBB:
20398   //  Allocate by call to runtime
20399   //
20400   // continueMBB:
20401   //  ...
20402   //  [rest of original BB]
20403   //
20404
20405   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20406   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20407   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20408
20409   MachineRegisterInfo &MRI = MF->getRegInfo();
20410   const TargetRegisterClass *AddrRegClass =
20411       getRegClassFor(getPointerTy(MF->getDataLayout()));
20412
20413   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20414     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20415     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20416     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20417     sizeVReg = MI->getOperand(1).getReg(),
20418     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20419
20420   MachineFunction::iterator MBBIter = BB;
20421   ++MBBIter;
20422
20423   MF->insert(MBBIter, bumpMBB);
20424   MF->insert(MBBIter, mallocMBB);
20425   MF->insert(MBBIter, continueMBB);
20426
20427   continueMBB->splice(continueMBB->begin(), BB,
20428                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20429   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20430
20431   // Add code to the main basic block to check if the stack limit has been hit,
20432   // and if so, jump to mallocMBB otherwise to bumpMBB.
20433   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20434   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20435     .addReg(tmpSPVReg).addReg(sizeVReg);
20436   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20437     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20438     .addReg(SPLimitVReg);
20439   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20440
20441   // bumpMBB simply decreases the stack pointer, since we know the current
20442   // stacklet has enough space.
20443   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20444     .addReg(SPLimitVReg);
20445   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20446     .addReg(SPLimitVReg);
20447   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20448
20449   // Calls into a routine in libgcc to allocate more space from the heap.
20450   const uint32_t *RegMask =
20451       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20452   if (IsLP64) {
20453     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20454       .addReg(sizeVReg);
20455     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20456       .addExternalSymbol("__morestack_allocate_stack_space")
20457       .addRegMask(RegMask)
20458       .addReg(X86::RDI, RegState::Implicit)
20459       .addReg(X86::RAX, RegState::ImplicitDefine);
20460   } else if (Is64Bit) {
20461     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20462       .addReg(sizeVReg);
20463     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20464       .addExternalSymbol("__morestack_allocate_stack_space")
20465       .addRegMask(RegMask)
20466       .addReg(X86::EDI, RegState::Implicit)
20467       .addReg(X86::EAX, RegState::ImplicitDefine);
20468   } else {
20469     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20470       .addImm(12);
20471     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20472     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20473       .addExternalSymbol("__morestack_allocate_stack_space")
20474       .addRegMask(RegMask)
20475       .addReg(X86::EAX, RegState::ImplicitDefine);
20476   }
20477
20478   if (!Is64Bit)
20479     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20480       .addImm(16);
20481
20482   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20483     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20484   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20485
20486   // Set up the CFG correctly.
20487   BB->addSuccessor(bumpMBB);
20488   BB->addSuccessor(mallocMBB);
20489   mallocMBB->addSuccessor(continueMBB);
20490   bumpMBB->addSuccessor(continueMBB);
20491
20492   // Take care of the PHI nodes.
20493   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20494           MI->getOperand(0).getReg())
20495     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20496     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20497
20498   // Delete the original pseudo instruction.
20499   MI->eraseFromParent();
20500
20501   // And we're done.
20502   return continueMBB;
20503 }
20504
20505 MachineBasicBlock *
20506 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20507                                         MachineBasicBlock *BB) const {
20508   DebugLoc DL = MI->getDebugLoc();
20509
20510   assert(!Subtarget->isTargetMachO());
20511
20512   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20513                                                     DL);
20514
20515   MI->eraseFromParent();   // The pseudo instruction is gone now.
20516   return BB;
20517 }
20518
20519 MachineBasicBlock *
20520 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20521                                       MachineBasicBlock *BB) const {
20522   // This is pretty easy.  We're taking the value that we received from
20523   // our load from the relocation, sticking it in either RDI (x86-64)
20524   // or EAX and doing an indirect call.  The return value will then
20525   // be in the normal return register.
20526   MachineFunction *F = BB->getParent();
20527   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20528   DebugLoc DL = MI->getDebugLoc();
20529
20530   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20531   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20532
20533   // Get a register mask for the lowered call.
20534   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20535   // proper register mask.
20536   const uint32_t *RegMask =
20537       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20538   if (Subtarget->is64Bit()) {
20539     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20540                                       TII->get(X86::MOV64rm), X86::RDI)
20541     .addReg(X86::RIP)
20542     .addImm(0).addReg(0)
20543     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20544                       MI->getOperand(3).getTargetFlags())
20545     .addReg(0);
20546     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20547     addDirectMem(MIB, X86::RDI);
20548     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20549   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20550     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20551                                       TII->get(X86::MOV32rm), X86::EAX)
20552     .addReg(0)
20553     .addImm(0).addReg(0)
20554     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20555                       MI->getOperand(3).getTargetFlags())
20556     .addReg(0);
20557     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20558     addDirectMem(MIB, X86::EAX);
20559     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20560   } else {
20561     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20562                                       TII->get(X86::MOV32rm), X86::EAX)
20563     .addReg(TII->getGlobalBaseReg(F))
20564     .addImm(0).addReg(0)
20565     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20566                       MI->getOperand(3).getTargetFlags())
20567     .addReg(0);
20568     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20569     addDirectMem(MIB, X86::EAX);
20570     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20571   }
20572
20573   MI->eraseFromParent(); // The pseudo instruction is gone now.
20574   return BB;
20575 }
20576
20577 MachineBasicBlock *
20578 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20579                                     MachineBasicBlock *MBB) const {
20580   DebugLoc DL = MI->getDebugLoc();
20581   MachineFunction *MF = MBB->getParent();
20582   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20583   MachineRegisterInfo &MRI = MF->getRegInfo();
20584
20585   const BasicBlock *BB = MBB->getBasicBlock();
20586   MachineFunction::iterator I = MBB;
20587   ++I;
20588
20589   // Memory Reference
20590   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20591   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20592
20593   unsigned DstReg;
20594   unsigned MemOpndSlot = 0;
20595
20596   unsigned CurOp = 0;
20597
20598   DstReg = MI->getOperand(CurOp++).getReg();
20599   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20600   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20601   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20602   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20603
20604   MemOpndSlot = CurOp;
20605
20606   MVT PVT = getPointerTy(MF->getDataLayout());
20607   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20608          "Invalid Pointer Size!");
20609
20610   // For v = setjmp(buf), we generate
20611   //
20612   // thisMBB:
20613   //  buf[LabelOffset] = restoreMBB
20614   //  SjLjSetup restoreMBB
20615   //
20616   // mainMBB:
20617   //  v_main = 0
20618   //
20619   // sinkMBB:
20620   //  v = phi(main, restore)
20621   //
20622   // restoreMBB:
20623   //  if base pointer being used, load it from frame
20624   //  v_restore = 1
20625
20626   MachineBasicBlock *thisMBB = MBB;
20627   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20628   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20629   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20630   MF->insert(I, mainMBB);
20631   MF->insert(I, sinkMBB);
20632   MF->push_back(restoreMBB);
20633
20634   MachineInstrBuilder MIB;
20635
20636   // Transfer the remainder of BB and its successor edges to sinkMBB.
20637   sinkMBB->splice(sinkMBB->begin(), MBB,
20638                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20639   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20640
20641   // thisMBB:
20642   unsigned PtrStoreOpc = 0;
20643   unsigned LabelReg = 0;
20644   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20645   Reloc::Model RM = MF->getTarget().getRelocationModel();
20646   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20647                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20648
20649   // Prepare IP either in reg or imm.
20650   if (!UseImmLabel) {
20651     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20652     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20653     LabelReg = MRI.createVirtualRegister(PtrRC);
20654     if (Subtarget->is64Bit()) {
20655       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20656               .addReg(X86::RIP)
20657               .addImm(0)
20658               .addReg(0)
20659               .addMBB(restoreMBB)
20660               .addReg(0);
20661     } else {
20662       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20663       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20664               .addReg(XII->getGlobalBaseReg(MF))
20665               .addImm(0)
20666               .addReg(0)
20667               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20668               .addReg(0);
20669     }
20670   } else
20671     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20672   // Store IP
20673   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20674   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20675     if (i == X86::AddrDisp)
20676       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20677     else
20678       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20679   }
20680   if (!UseImmLabel)
20681     MIB.addReg(LabelReg);
20682   else
20683     MIB.addMBB(restoreMBB);
20684   MIB.setMemRefs(MMOBegin, MMOEnd);
20685   // Setup
20686   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20687           .addMBB(restoreMBB);
20688
20689   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20690   MIB.addRegMask(RegInfo->getNoPreservedMask());
20691   thisMBB->addSuccessor(mainMBB);
20692   thisMBB->addSuccessor(restoreMBB);
20693
20694   // mainMBB:
20695   //  EAX = 0
20696   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20697   mainMBB->addSuccessor(sinkMBB);
20698
20699   // sinkMBB:
20700   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20701           TII->get(X86::PHI), DstReg)
20702     .addReg(mainDstReg).addMBB(mainMBB)
20703     .addReg(restoreDstReg).addMBB(restoreMBB);
20704
20705   // restoreMBB:
20706   if (RegInfo->hasBasePointer(*MF)) {
20707     const bool Uses64BitFramePtr =
20708         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20709     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20710     X86FI->setRestoreBasePointer(MF);
20711     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20712     unsigned BasePtr = RegInfo->getBaseRegister();
20713     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20714     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20715                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20716       .setMIFlag(MachineInstr::FrameSetup);
20717   }
20718   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20719   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20720   restoreMBB->addSuccessor(sinkMBB);
20721
20722   MI->eraseFromParent();
20723   return sinkMBB;
20724 }
20725
20726 MachineBasicBlock *
20727 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20728                                      MachineBasicBlock *MBB) const {
20729   DebugLoc DL = MI->getDebugLoc();
20730   MachineFunction *MF = MBB->getParent();
20731   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20732   MachineRegisterInfo &MRI = MF->getRegInfo();
20733
20734   // Memory Reference
20735   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20736   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20737
20738   MVT PVT = getPointerTy(MF->getDataLayout());
20739   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20740          "Invalid Pointer Size!");
20741
20742   const TargetRegisterClass *RC =
20743     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20744   unsigned Tmp = MRI.createVirtualRegister(RC);
20745   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20746   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20747   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20748   unsigned SP = RegInfo->getStackRegister();
20749
20750   MachineInstrBuilder MIB;
20751
20752   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20753   const int64_t SPOffset = 2 * PVT.getStoreSize();
20754
20755   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20756   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20757
20758   // Reload FP
20759   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20760   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20761     MIB.addOperand(MI->getOperand(i));
20762   MIB.setMemRefs(MMOBegin, MMOEnd);
20763   // Reload IP
20764   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20765   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20766     if (i == X86::AddrDisp)
20767       MIB.addDisp(MI->getOperand(i), LabelOffset);
20768     else
20769       MIB.addOperand(MI->getOperand(i));
20770   }
20771   MIB.setMemRefs(MMOBegin, MMOEnd);
20772   // Reload SP
20773   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20774   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20775     if (i == X86::AddrDisp)
20776       MIB.addDisp(MI->getOperand(i), SPOffset);
20777     else
20778       MIB.addOperand(MI->getOperand(i));
20779   }
20780   MIB.setMemRefs(MMOBegin, MMOEnd);
20781   // Jump
20782   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20783
20784   MI->eraseFromParent();
20785   return MBB;
20786 }
20787
20788 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20789 // accumulator loops. Writing back to the accumulator allows the coalescer
20790 // to remove extra copies in the loop.
20791 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20792 MachineBasicBlock *
20793 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20794                                  MachineBasicBlock *MBB) const {
20795   MachineOperand &AddendOp = MI->getOperand(3);
20796
20797   // Bail out early if the addend isn't a register - we can't switch these.
20798   if (!AddendOp.isReg())
20799     return MBB;
20800
20801   MachineFunction &MF = *MBB->getParent();
20802   MachineRegisterInfo &MRI = MF.getRegInfo();
20803
20804   // Check whether the addend is defined by a PHI:
20805   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20806   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20807   if (!AddendDef.isPHI())
20808     return MBB;
20809
20810   // Look for the following pattern:
20811   // loop:
20812   //   %addend = phi [%entry, 0], [%loop, %result]
20813   //   ...
20814   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20815
20816   // Replace with:
20817   //   loop:
20818   //   %addend = phi [%entry, 0], [%loop, %result]
20819   //   ...
20820   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20821
20822   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20823     assert(AddendDef.getOperand(i).isReg());
20824     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20825     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20826     if (&PHISrcInst == MI) {
20827       // Found a matching instruction.
20828       unsigned NewFMAOpc = 0;
20829       switch (MI->getOpcode()) {
20830         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20831         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20832         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20833         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20834         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20835         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20836         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20837         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20838         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20839         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20840         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20841         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20842         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20843         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20844         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20845         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20846         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20847         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20848         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20849         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20850
20851         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20852         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20853         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20854         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20855         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20856         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20857         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20858         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20859         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20860         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20861         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20862         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20863         default: llvm_unreachable("Unrecognized FMA variant.");
20864       }
20865
20866       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20867       MachineInstrBuilder MIB =
20868         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20869         .addOperand(MI->getOperand(0))
20870         .addOperand(MI->getOperand(3))
20871         .addOperand(MI->getOperand(2))
20872         .addOperand(MI->getOperand(1));
20873       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20874       MI->eraseFromParent();
20875     }
20876   }
20877
20878   return MBB;
20879 }
20880
20881 MachineBasicBlock *
20882 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20883                                                MachineBasicBlock *BB) const {
20884   switch (MI->getOpcode()) {
20885   default: llvm_unreachable("Unexpected instr type to insert");
20886   case X86::TAILJMPd64:
20887   case X86::TAILJMPr64:
20888   case X86::TAILJMPm64:
20889   case X86::TAILJMPd64_REX:
20890   case X86::TAILJMPr64_REX:
20891   case X86::TAILJMPm64_REX:
20892     llvm_unreachable("TAILJMP64 would not be touched here.");
20893   case X86::TCRETURNdi64:
20894   case X86::TCRETURNri64:
20895   case X86::TCRETURNmi64:
20896     return BB;
20897   case X86::WIN_ALLOCA:
20898     return EmitLoweredWinAlloca(MI, BB);
20899   case X86::SEG_ALLOCA_32:
20900   case X86::SEG_ALLOCA_64:
20901     return EmitLoweredSegAlloca(MI, BB);
20902   case X86::TLSCall_32:
20903   case X86::TLSCall_64:
20904     return EmitLoweredTLSCall(MI, BB);
20905   case X86::CMOV_FR32:
20906   case X86::CMOV_FR64:
20907   case X86::CMOV_GR8:
20908   case X86::CMOV_GR16:
20909   case X86::CMOV_GR32:
20910   case X86::CMOV_RFP32:
20911   case X86::CMOV_RFP64:
20912   case X86::CMOV_RFP80:
20913   case X86::CMOV_V2F64:
20914   case X86::CMOV_V2I64:
20915   case X86::CMOV_V4F32:
20916   case X86::CMOV_V4F64:
20917   case X86::CMOV_V4I64:
20918   case X86::CMOV_V16F32:
20919   case X86::CMOV_V8F32:
20920   case X86::CMOV_V8F64:
20921   case X86::CMOV_V8I64:
20922   case X86::CMOV_V8I1:
20923   case X86::CMOV_V16I1:
20924   case X86::CMOV_V32I1:
20925   case X86::CMOV_V64I1:
20926     return EmitLoweredSelect(MI, BB);
20927
20928   case X86::RELEASE_FADD32mr:
20929   case X86::RELEASE_FADD64mr:
20930     return EmitLoweredAtomicFP(MI, BB);
20931
20932   case X86::FP32_TO_INT16_IN_MEM:
20933   case X86::FP32_TO_INT32_IN_MEM:
20934   case X86::FP32_TO_INT64_IN_MEM:
20935   case X86::FP64_TO_INT16_IN_MEM:
20936   case X86::FP64_TO_INT32_IN_MEM:
20937   case X86::FP64_TO_INT64_IN_MEM:
20938   case X86::FP80_TO_INT16_IN_MEM:
20939   case X86::FP80_TO_INT32_IN_MEM:
20940   case X86::FP80_TO_INT64_IN_MEM: {
20941     MachineFunction *F = BB->getParent();
20942     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20943     DebugLoc DL = MI->getDebugLoc();
20944
20945     // Change the floating point control register to use "round towards zero"
20946     // mode when truncating to an integer value.
20947     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20948     addFrameReference(BuildMI(*BB, MI, DL,
20949                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20950
20951     // Load the old value of the high byte of the control word...
20952     unsigned OldCW =
20953       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20954     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20955                       CWFrameIdx);
20956
20957     // Set the high part to be round to zero...
20958     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20959       .addImm(0xC7F);
20960
20961     // Reload the modified control word now...
20962     addFrameReference(BuildMI(*BB, MI, DL,
20963                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20964
20965     // Restore the memory image of control word to original value
20966     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20967       .addReg(OldCW);
20968
20969     // Get the X86 opcode to use.
20970     unsigned Opc;
20971     switch (MI->getOpcode()) {
20972     default: llvm_unreachable("illegal opcode!");
20973     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20974     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20975     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20976     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20977     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20978     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20979     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20980     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20981     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20982     }
20983
20984     X86AddressMode AM;
20985     MachineOperand &Op = MI->getOperand(0);
20986     if (Op.isReg()) {
20987       AM.BaseType = X86AddressMode::RegBase;
20988       AM.Base.Reg = Op.getReg();
20989     } else {
20990       AM.BaseType = X86AddressMode::FrameIndexBase;
20991       AM.Base.FrameIndex = Op.getIndex();
20992     }
20993     Op = MI->getOperand(1);
20994     if (Op.isImm())
20995       AM.Scale = Op.getImm();
20996     Op = MI->getOperand(2);
20997     if (Op.isImm())
20998       AM.IndexReg = Op.getImm();
20999     Op = MI->getOperand(3);
21000     if (Op.isGlobal()) {
21001       AM.GV = Op.getGlobal();
21002     } else {
21003       AM.Disp = Op.getImm();
21004     }
21005     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21006                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21007
21008     // Reload the original control word now.
21009     addFrameReference(BuildMI(*BB, MI, DL,
21010                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21011
21012     MI->eraseFromParent();   // The pseudo instruction is gone now.
21013     return BB;
21014   }
21015     // String/text processing lowering.
21016   case X86::PCMPISTRM128REG:
21017   case X86::VPCMPISTRM128REG:
21018   case X86::PCMPISTRM128MEM:
21019   case X86::VPCMPISTRM128MEM:
21020   case X86::PCMPESTRM128REG:
21021   case X86::VPCMPESTRM128REG:
21022   case X86::PCMPESTRM128MEM:
21023   case X86::VPCMPESTRM128MEM:
21024     assert(Subtarget->hasSSE42() &&
21025            "Target must have SSE4.2 or AVX features enabled");
21026     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21027
21028   // String/text processing lowering.
21029   case X86::PCMPISTRIREG:
21030   case X86::VPCMPISTRIREG:
21031   case X86::PCMPISTRIMEM:
21032   case X86::VPCMPISTRIMEM:
21033   case X86::PCMPESTRIREG:
21034   case X86::VPCMPESTRIREG:
21035   case X86::PCMPESTRIMEM:
21036   case X86::VPCMPESTRIMEM:
21037     assert(Subtarget->hasSSE42() &&
21038            "Target must have SSE4.2 or AVX features enabled");
21039     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21040
21041   // Thread synchronization.
21042   case X86::MONITOR:
21043     return EmitMonitor(MI, BB, Subtarget);
21044
21045   // xbegin
21046   case X86::XBEGIN:
21047     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21048
21049   case X86::VASTART_SAVE_XMM_REGS:
21050     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21051
21052   case X86::VAARG_64:
21053     return EmitVAARG64WithCustomInserter(MI, BB);
21054
21055   case X86::EH_SjLj_SetJmp32:
21056   case X86::EH_SjLj_SetJmp64:
21057     return emitEHSjLjSetJmp(MI, BB);
21058
21059   case X86::EH_SjLj_LongJmp32:
21060   case X86::EH_SjLj_LongJmp64:
21061     return emitEHSjLjLongJmp(MI, BB);
21062
21063   case TargetOpcode::STATEPOINT:
21064     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21065     // this point in the process.  We diverge later.
21066     return emitPatchPoint(MI, BB);
21067
21068   case TargetOpcode::STACKMAP:
21069   case TargetOpcode::PATCHPOINT:
21070     return emitPatchPoint(MI, BB);
21071
21072   case X86::VFMADDPDr213r:
21073   case X86::VFMADDPSr213r:
21074   case X86::VFMADDSDr213r:
21075   case X86::VFMADDSSr213r:
21076   case X86::VFMSUBPDr213r:
21077   case X86::VFMSUBPSr213r:
21078   case X86::VFMSUBSDr213r:
21079   case X86::VFMSUBSSr213r:
21080   case X86::VFNMADDPDr213r:
21081   case X86::VFNMADDPSr213r:
21082   case X86::VFNMADDSDr213r:
21083   case X86::VFNMADDSSr213r:
21084   case X86::VFNMSUBPDr213r:
21085   case X86::VFNMSUBPSr213r:
21086   case X86::VFNMSUBSDr213r:
21087   case X86::VFNMSUBSSr213r:
21088   case X86::VFMADDSUBPDr213r:
21089   case X86::VFMADDSUBPSr213r:
21090   case X86::VFMSUBADDPDr213r:
21091   case X86::VFMSUBADDPSr213r:
21092   case X86::VFMADDPDr213rY:
21093   case X86::VFMADDPSr213rY:
21094   case X86::VFMSUBPDr213rY:
21095   case X86::VFMSUBPSr213rY:
21096   case X86::VFNMADDPDr213rY:
21097   case X86::VFNMADDPSr213rY:
21098   case X86::VFNMSUBPDr213rY:
21099   case X86::VFNMSUBPSr213rY:
21100   case X86::VFMADDSUBPDr213rY:
21101   case X86::VFMADDSUBPSr213rY:
21102   case X86::VFMSUBADDPDr213rY:
21103   case X86::VFMSUBADDPSr213rY:
21104     return emitFMA3Instr(MI, BB);
21105   }
21106 }
21107
21108 //===----------------------------------------------------------------------===//
21109 //                           X86 Optimization Hooks
21110 //===----------------------------------------------------------------------===//
21111
21112 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21113                                                       APInt &KnownZero,
21114                                                       APInt &KnownOne,
21115                                                       const SelectionDAG &DAG,
21116                                                       unsigned Depth) const {
21117   unsigned BitWidth = KnownZero.getBitWidth();
21118   unsigned Opc = Op.getOpcode();
21119   assert((Opc >= ISD::BUILTIN_OP_END ||
21120           Opc == ISD::INTRINSIC_WO_CHAIN ||
21121           Opc == ISD::INTRINSIC_W_CHAIN ||
21122           Opc == ISD::INTRINSIC_VOID) &&
21123          "Should use MaskedValueIsZero if you don't know whether Op"
21124          " is a target node!");
21125
21126   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21127   switch (Opc) {
21128   default: break;
21129   case X86ISD::ADD:
21130   case X86ISD::SUB:
21131   case X86ISD::ADC:
21132   case X86ISD::SBB:
21133   case X86ISD::SMUL:
21134   case X86ISD::UMUL:
21135   case X86ISD::INC:
21136   case X86ISD::DEC:
21137   case X86ISD::OR:
21138   case X86ISD::XOR:
21139   case X86ISD::AND:
21140     // These nodes' second result is a boolean.
21141     if (Op.getResNo() == 0)
21142       break;
21143     // Fallthrough
21144   case X86ISD::SETCC:
21145     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21146     break;
21147   case ISD::INTRINSIC_WO_CHAIN: {
21148     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21149     unsigned NumLoBits = 0;
21150     switch (IntId) {
21151     default: break;
21152     case Intrinsic::x86_sse_movmsk_ps:
21153     case Intrinsic::x86_avx_movmsk_ps_256:
21154     case Intrinsic::x86_sse2_movmsk_pd:
21155     case Intrinsic::x86_avx_movmsk_pd_256:
21156     case Intrinsic::x86_mmx_pmovmskb:
21157     case Intrinsic::x86_sse2_pmovmskb_128:
21158     case Intrinsic::x86_avx2_pmovmskb: {
21159       // High bits of movmskp{s|d}, pmovmskb are known zero.
21160       switch (IntId) {
21161         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21162         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21163         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21164         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21165         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21166         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21167         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21168         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21169       }
21170       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21171       break;
21172     }
21173     }
21174     break;
21175   }
21176   }
21177 }
21178
21179 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21180   SDValue Op,
21181   const SelectionDAG &,
21182   unsigned Depth) const {
21183   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21184   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21185     return Op.getValueType().getScalarType().getSizeInBits();
21186
21187   // Fallback case.
21188   return 1;
21189 }
21190
21191 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21192 /// node is a GlobalAddress + offset.
21193 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21194                                        const GlobalValue* &GA,
21195                                        int64_t &Offset) const {
21196   if (N->getOpcode() == X86ISD::Wrapper) {
21197     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21198       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21199       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21200       return true;
21201     }
21202   }
21203   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21204 }
21205
21206 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21207 /// same as extracting the high 128-bit part of 256-bit vector and then
21208 /// inserting the result into the low part of a new 256-bit vector
21209 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21210   EVT VT = SVOp->getValueType(0);
21211   unsigned NumElems = VT.getVectorNumElements();
21212
21213   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21214   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21215     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21216         SVOp->getMaskElt(j) >= 0)
21217       return false;
21218
21219   return true;
21220 }
21221
21222 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21223 /// same as extracting the low 128-bit part of 256-bit vector and then
21224 /// inserting the result into the high part of a new 256-bit vector
21225 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21226   EVT VT = SVOp->getValueType(0);
21227   unsigned NumElems = VT.getVectorNumElements();
21228
21229   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21230   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21231     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21232         SVOp->getMaskElt(j) >= 0)
21233       return false;
21234
21235   return true;
21236 }
21237
21238 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21239 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21240                                         TargetLowering::DAGCombinerInfo &DCI,
21241                                         const X86Subtarget* Subtarget) {
21242   SDLoc dl(N);
21243   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21244   SDValue V1 = SVOp->getOperand(0);
21245   SDValue V2 = SVOp->getOperand(1);
21246   EVT VT = SVOp->getValueType(0);
21247   unsigned NumElems = VT.getVectorNumElements();
21248
21249   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21250       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21251     //
21252     //                   0,0,0,...
21253     //                      |
21254     //    V      UNDEF    BUILD_VECTOR    UNDEF
21255     //     \      /           \           /
21256     //  CONCAT_VECTOR         CONCAT_VECTOR
21257     //         \                  /
21258     //          \                /
21259     //          RESULT: V + zero extended
21260     //
21261     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21262         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21263         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21264       return SDValue();
21265
21266     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21267       return SDValue();
21268
21269     // To match the shuffle mask, the first half of the mask should
21270     // be exactly the first vector, and all the rest a splat with the
21271     // first element of the second one.
21272     for (unsigned i = 0; i != NumElems/2; ++i)
21273       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21274           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21275         return SDValue();
21276
21277     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21278     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21279       if (Ld->hasNUsesOfValue(1, 0)) {
21280         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21281         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21282         SDValue ResNode =
21283           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21284                                   Ld->getMemoryVT(),
21285                                   Ld->getPointerInfo(),
21286                                   Ld->getAlignment(),
21287                                   false/*isVolatile*/, true/*ReadMem*/,
21288                                   false/*WriteMem*/);
21289
21290         // Make sure the newly-created LOAD is in the same position as Ld in
21291         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21292         // and update uses of Ld's output chain to use the TokenFactor.
21293         if (Ld->hasAnyUseOfValue(1)) {
21294           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21295                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21296           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21297           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21298                                  SDValue(ResNode.getNode(), 1));
21299         }
21300
21301         return DAG.getBitcast(VT, ResNode);
21302       }
21303     }
21304
21305     // Emit a zeroed vector and insert the desired subvector on its
21306     // first half.
21307     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21308     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21309     return DCI.CombineTo(N, InsV);
21310   }
21311
21312   //===--------------------------------------------------------------------===//
21313   // Combine some shuffles into subvector extracts and inserts:
21314   //
21315
21316   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21317   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21318     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21319     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21320     return DCI.CombineTo(N, InsV);
21321   }
21322
21323   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21324   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21325     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21326     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21327     return DCI.CombineTo(N, InsV);
21328   }
21329
21330   return SDValue();
21331 }
21332
21333 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21334 /// possible.
21335 ///
21336 /// This is the leaf of the recursive combinine below. When we have found some
21337 /// chain of single-use x86 shuffle instructions and accumulated the combined
21338 /// shuffle mask represented by them, this will try to pattern match that mask
21339 /// into either a single instruction if there is a special purpose instruction
21340 /// for this operation, or into a PSHUFB instruction which is a fully general
21341 /// instruction but should only be used to replace chains over a certain depth.
21342 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21343                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21344                                    TargetLowering::DAGCombinerInfo &DCI,
21345                                    const X86Subtarget *Subtarget) {
21346   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21347
21348   // Find the operand that enters the chain. Note that multiple uses are OK
21349   // here, we're not going to remove the operand we find.
21350   SDValue Input = Op.getOperand(0);
21351   while (Input.getOpcode() == ISD::BITCAST)
21352     Input = Input.getOperand(0);
21353
21354   MVT VT = Input.getSimpleValueType();
21355   MVT RootVT = Root.getSimpleValueType();
21356   SDLoc DL(Root);
21357
21358   // Just remove no-op shuffle masks.
21359   if (Mask.size() == 1) {
21360     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21361                   /*AddTo*/ true);
21362     return true;
21363   }
21364
21365   // Use the float domain if the operand type is a floating point type.
21366   bool FloatDomain = VT.isFloatingPoint();
21367
21368   // For floating point shuffles, we don't have free copies in the shuffle
21369   // instructions or the ability to load as part of the instruction, so
21370   // canonicalize their shuffles to UNPCK or MOV variants.
21371   //
21372   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21373   // vectors because it can have a load folded into it that UNPCK cannot. This
21374   // doesn't preclude something switching to the shorter encoding post-RA.
21375   //
21376   // FIXME: Should teach these routines about AVX vector widths.
21377   if (FloatDomain && VT.getSizeInBits() == 128) {
21378     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21379       bool Lo = Mask.equals({0, 0});
21380       unsigned Shuffle;
21381       MVT ShuffleVT;
21382       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21383       // is no slower than UNPCKLPD but has the option to fold the input operand
21384       // into even an unaligned memory load.
21385       if (Lo && Subtarget->hasSSE3()) {
21386         Shuffle = X86ISD::MOVDDUP;
21387         ShuffleVT = MVT::v2f64;
21388       } else {
21389         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21390         // than the UNPCK variants.
21391         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21392         ShuffleVT = MVT::v4f32;
21393       }
21394       if (Depth == 1 && Root->getOpcode() == Shuffle)
21395         return false; // Nothing to do!
21396       Op = DAG.getBitcast(ShuffleVT, Input);
21397       DCI.AddToWorklist(Op.getNode());
21398       if (Shuffle == X86ISD::MOVDDUP)
21399         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21400       else
21401         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21402       DCI.AddToWorklist(Op.getNode());
21403       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21404                     /*AddTo*/ true);
21405       return true;
21406     }
21407     if (Subtarget->hasSSE3() &&
21408         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21409       bool Lo = Mask.equals({0, 0, 2, 2});
21410       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21411       MVT ShuffleVT = MVT::v4f32;
21412       if (Depth == 1 && Root->getOpcode() == Shuffle)
21413         return false; // Nothing to do!
21414       Op = DAG.getBitcast(ShuffleVT, Input);
21415       DCI.AddToWorklist(Op.getNode());
21416       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21417       DCI.AddToWorklist(Op.getNode());
21418       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21419                     /*AddTo*/ true);
21420       return true;
21421     }
21422     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21423       bool Lo = Mask.equals({0, 0, 1, 1});
21424       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21425       MVT ShuffleVT = MVT::v4f32;
21426       if (Depth == 1 && Root->getOpcode() == Shuffle)
21427         return false; // Nothing to do!
21428       Op = DAG.getBitcast(ShuffleVT, Input);
21429       DCI.AddToWorklist(Op.getNode());
21430       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21431       DCI.AddToWorklist(Op.getNode());
21432       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21433                     /*AddTo*/ true);
21434       return true;
21435     }
21436   }
21437
21438   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21439   // variants as none of these have single-instruction variants that are
21440   // superior to the UNPCK formulation.
21441   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21442       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21443        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21444        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21445        Mask.equals(
21446            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21447     bool Lo = Mask[0] == 0;
21448     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21449     if (Depth == 1 && Root->getOpcode() == Shuffle)
21450       return false; // Nothing to do!
21451     MVT ShuffleVT;
21452     switch (Mask.size()) {
21453     case 8:
21454       ShuffleVT = MVT::v8i16;
21455       break;
21456     case 16:
21457       ShuffleVT = MVT::v16i8;
21458       break;
21459     default:
21460       llvm_unreachable("Impossible mask size!");
21461     };
21462     Op = DAG.getBitcast(ShuffleVT, Input);
21463     DCI.AddToWorklist(Op.getNode());
21464     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21465     DCI.AddToWorklist(Op.getNode());
21466     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21467                   /*AddTo*/ true);
21468     return true;
21469   }
21470
21471   // Don't try to re-form single instruction chains under any circumstances now
21472   // that we've done encoding canonicalization for them.
21473   if (Depth < 2)
21474     return false;
21475
21476   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21477   // can replace them with a single PSHUFB instruction profitably. Intel's
21478   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21479   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21480   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21481     SmallVector<SDValue, 16> PSHUFBMask;
21482     int NumBytes = VT.getSizeInBits() / 8;
21483     int Ratio = NumBytes / Mask.size();
21484     for (int i = 0; i < NumBytes; ++i) {
21485       if (Mask[i / Ratio] == SM_SentinelUndef) {
21486         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21487         continue;
21488       }
21489       int M = Mask[i / Ratio] != SM_SentinelZero
21490                   ? Ratio * Mask[i / Ratio] + i % Ratio
21491                   : 255;
21492       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21493     }
21494     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21495     Op = DAG.getBitcast(ByteVT, Input);
21496     DCI.AddToWorklist(Op.getNode());
21497     SDValue PSHUFBMaskOp =
21498         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21499     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21500     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21501     DCI.AddToWorklist(Op.getNode());
21502     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21503                   /*AddTo*/ true);
21504     return true;
21505   }
21506
21507   // Failed to find any combines.
21508   return false;
21509 }
21510
21511 /// \brief Fully generic combining of x86 shuffle instructions.
21512 ///
21513 /// This should be the last combine run over the x86 shuffle instructions. Once
21514 /// they have been fully optimized, this will recursively consider all chains
21515 /// of single-use shuffle instructions, build a generic model of the cumulative
21516 /// shuffle operation, and check for simpler instructions which implement this
21517 /// operation. We use this primarily for two purposes:
21518 ///
21519 /// 1) Collapse generic shuffles to specialized single instructions when
21520 ///    equivalent. In most cases, this is just an encoding size win, but
21521 ///    sometimes we will collapse multiple generic shuffles into a single
21522 ///    special-purpose shuffle.
21523 /// 2) Look for sequences of shuffle instructions with 3 or more total
21524 ///    instructions, and replace them with the slightly more expensive SSSE3
21525 ///    PSHUFB instruction if available. We do this as the last combining step
21526 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21527 ///    a suitable short sequence of other instructions. The PHUFB will either
21528 ///    use a register or have to read from memory and so is slightly (but only
21529 ///    slightly) more expensive than the other shuffle instructions.
21530 ///
21531 /// Because this is inherently a quadratic operation (for each shuffle in
21532 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21533 /// This should never be an issue in practice as the shuffle lowering doesn't
21534 /// produce sequences of more than 8 instructions.
21535 ///
21536 /// FIXME: We will currently miss some cases where the redundant shuffling
21537 /// would simplify under the threshold for PSHUFB formation because of
21538 /// combine-ordering. To fix this, we should do the redundant instruction
21539 /// combining in this recursive walk.
21540 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21541                                           ArrayRef<int> RootMask,
21542                                           int Depth, bool HasPSHUFB,
21543                                           SelectionDAG &DAG,
21544                                           TargetLowering::DAGCombinerInfo &DCI,
21545                                           const X86Subtarget *Subtarget) {
21546   // Bound the depth of our recursive combine because this is ultimately
21547   // quadratic in nature.
21548   if (Depth > 8)
21549     return false;
21550
21551   // Directly rip through bitcasts to find the underlying operand.
21552   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21553     Op = Op.getOperand(0);
21554
21555   MVT VT = Op.getSimpleValueType();
21556   if (!VT.isVector())
21557     return false; // Bail if we hit a non-vector.
21558
21559   assert(Root.getSimpleValueType().isVector() &&
21560          "Shuffles operate on vector types!");
21561   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21562          "Can only combine shuffles of the same vector register size.");
21563
21564   if (!isTargetShuffle(Op.getOpcode()))
21565     return false;
21566   SmallVector<int, 16> OpMask;
21567   bool IsUnary;
21568   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21569   // We only can combine unary shuffles which we can decode the mask for.
21570   if (!HaveMask || !IsUnary)
21571     return false;
21572
21573   assert(VT.getVectorNumElements() == OpMask.size() &&
21574          "Different mask size from vector size!");
21575   assert(((RootMask.size() > OpMask.size() &&
21576            RootMask.size() % OpMask.size() == 0) ||
21577           (OpMask.size() > RootMask.size() &&
21578            OpMask.size() % RootMask.size() == 0) ||
21579           OpMask.size() == RootMask.size()) &&
21580          "The smaller number of elements must divide the larger.");
21581   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21582   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21583   assert(((RootRatio == 1 && OpRatio == 1) ||
21584           (RootRatio == 1) != (OpRatio == 1)) &&
21585          "Must not have a ratio for both incoming and op masks!");
21586
21587   SmallVector<int, 16> Mask;
21588   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21589
21590   // Merge this shuffle operation's mask into our accumulated mask. Note that
21591   // this shuffle's mask will be the first applied to the input, followed by the
21592   // root mask to get us all the way to the root value arrangement. The reason
21593   // for this order is that we are recursing up the operation chain.
21594   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21595     int RootIdx = i / RootRatio;
21596     if (RootMask[RootIdx] < 0) {
21597       // This is a zero or undef lane, we're done.
21598       Mask.push_back(RootMask[RootIdx]);
21599       continue;
21600     }
21601
21602     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21603     int OpIdx = RootMaskedIdx / OpRatio;
21604     if (OpMask[OpIdx] < 0) {
21605       // The incoming lanes are zero or undef, it doesn't matter which ones we
21606       // are using.
21607       Mask.push_back(OpMask[OpIdx]);
21608       continue;
21609     }
21610
21611     // Ok, we have non-zero lanes, map them through.
21612     Mask.push_back(OpMask[OpIdx] * OpRatio +
21613                    RootMaskedIdx % OpRatio);
21614   }
21615
21616   // See if we can recurse into the operand to combine more things.
21617   switch (Op.getOpcode()) {
21618     case X86ISD::PSHUFB:
21619       HasPSHUFB = true;
21620     case X86ISD::PSHUFD:
21621     case X86ISD::PSHUFHW:
21622     case X86ISD::PSHUFLW:
21623       if (Op.getOperand(0).hasOneUse() &&
21624           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21625                                         HasPSHUFB, DAG, DCI, Subtarget))
21626         return true;
21627       break;
21628
21629     case X86ISD::UNPCKL:
21630     case X86ISD::UNPCKH:
21631       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21632       // We can't check for single use, we have to check that this shuffle is the only user.
21633       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21634           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21635                                         HasPSHUFB, DAG, DCI, Subtarget))
21636           return true;
21637       break;
21638   }
21639
21640   // Minor canonicalization of the accumulated shuffle mask to make it easier
21641   // to match below. All this does is detect masks with squential pairs of
21642   // elements, and shrink them to the half-width mask. It does this in a loop
21643   // so it will reduce the size of the mask to the minimal width mask which
21644   // performs an equivalent shuffle.
21645   SmallVector<int, 16> WidenedMask;
21646   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21647     Mask = std::move(WidenedMask);
21648     WidenedMask.clear();
21649   }
21650
21651   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21652                                 Subtarget);
21653 }
21654
21655 /// \brief Get the PSHUF-style mask from PSHUF node.
21656 ///
21657 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21658 /// PSHUF-style masks that can be reused with such instructions.
21659 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21660   MVT VT = N.getSimpleValueType();
21661   SmallVector<int, 4> Mask;
21662   bool IsUnary;
21663   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21664   (void)HaveMask;
21665   assert(HaveMask);
21666
21667   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21668   // matter. Check that the upper masks are repeats and remove them.
21669   if (VT.getSizeInBits() > 128) {
21670     int LaneElts = 128 / VT.getScalarSizeInBits();
21671 #ifndef NDEBUG
21672     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21673       for (int j = 0; j < LaneElts; ++j)
21674         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21675                "Mask doesn't repeat in high 128-bit lanes!");
21676 #endif
21677     Mask.resize(LaneElts);
21678   }
21679
21680   switch (N.getOpcode()) {
21681   case X86ISD::PSHUFD:
21682     return Mask;
21683   case X86ISD::PSHUFLW:
21684     Mask.resize(4);
21685     return Mask;
21686   case X86ISD::PSHUFHW:
21687     Mask.erase(Mask.begin(), Mask.begin() + 4);
21688     for (int &M : Mask)
21689       M -= 4;
21690     return Mask;
21691   default:
21692     llvm_unreachable("No valid shuffle instruction found!");
21693   }
21694 }
21695
21696 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21697 ///
21698 /// We walk up the chain and look for a combinable shuffle, skipping over
21699 /// shuffles that we could hoist this shuffle's transformation past without
21700 /// altering anything.
21701 static SDValue
21702 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21703                              SelectionDAG &DAG,
21704                              TargetLowering::DAGCombinerInfo &DCI) {
21705   assert(N.getOpcode() == X86ISD::PSHUFD &&
21706          "Called with something other than an x86 128-bit half shuffle!");
21707   SDLoc DL(N);
21708
21709   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21710   // of the shuffles in the chain so that we can form a fresh chain to replace
21711   // this one.
21712   SmallVector<SDValue, 8> Chain;
21713   SDValue V = N.getOperand(0);
21714   for (; V.hasOneUse(); V = V.getOperand(0)) {
21715     switch (V.getOpcode()) {
21716     default:
21717       return SDValue(); // Nothing combined!
21718
21719     case ISD::BITCAST:
21720       // Skip bitcasts as we always know the type for the target specific
21721       // instructions.
21722       continue;
21723
21724     case X86ISD::PSHUFD:
21725       // Found another dword shuffle.
21726       break;
21727
21728     case X86ISD::PSHUFLW:
21729       // Check that the low words (being shuffled) are the identity in the
21730       // dword shuffle, and the high words are self-contained.
21731       if (Mask[0] != 0 || Mask[1] != 1 ||
21732           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21733         return SDValue();
21734
21735       Chain.push_back(V);
21736       continue;
21737
21738     case X86ISD::PSHUFHW:
21739       // Check that the high words (being shuffled) are the identity in the
21740       // dword shuffle, and the low words are self-contained.
21741       if (Mask[2] != 2 || Mask[3] != 3 ||
21742           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21743         return SDValue();
21744
21745       Chain.push_back(V);
21746       continue;
21747
21748     case X86ISD::UNPCKL:
21749     case X86ISD::UNPCKH:
21750       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21751       // shuffle into a preceding word shuffle.
21752       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21753           V.getSimpleValueType().getScalarType() != MVT::i16)
21754         return SDValue();
21755
21756       // Search for a half-shuffle which we can combine with.
21757       unsigned CombineOp =
21758           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21759       if (V.getOperand(0) != V.getOperand(1) ||
21760           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21761         return SDValue();
21762       Chain.push_back(V);
21763       V = V.getOperand(0);
21764       do {
21765         switch (V.getOpcode()) {
21766         default:
21767           return SDValue(); // Nothing to combine.
21768
21769         case X86ISD::PSHUFLW:
21770         case X86ISD::PSHUFHW:
21771           if (V.getOpcode() == CombineOp)
21772             break;
21773
21774           Chain.push_back(V);
21775
21776           // Fallthrough!
21777         case ISD::BITCAST:
21778           V = V.getOperand(0);
21779           continue;
21780         }
21781         break;
21782       } while (V.hasOneUse());
21783       break;
21784     }
21785     // Break out of the loop if we break out of the switch.
21786     break;
21787   }
21788
21789   if (!V.hasOneUse())
21790     // We fell out of the loop without finding a viable combining instruction.
21791     return SDValue();
21792
21793   // Merge this node's mask and our incoming mask.
21794   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21795   for (int &M : Mask)
21796     M = VMask[M];
21797   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21798                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21799
21800   // Rebuild the chain around this new shuffle.
21801   while (!Chain.empty()) {
21802     SDValue W = Chain.pop_back_val();
21803
21804     if (V.getValueType() != W.getOperand(0).getValueType())
21805       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21806
21807     switch (W.getOpcode()) {
21808     default:
21809       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21810
21811     case X86ISD::UNPCKL:
21812     case X86ISD::UNPCKH:
21813       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21814       break;
21815
21816     case X86ISD::PSHUFD:
21817     case X86ISD::PSHUFLW:
21818     case X86ISD::PSHUFHW:
21819       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21820       break;
21821     }
21822   }
21823   if (V.getValueType() != N.getValueType())
21824     V = DAG.getBitcast(N.getValueType(), V);
21825
21826   // Return the new chain to replace N.
21827   return V;
21828 }
21829
21830 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21831 ///
21832 /// We walk up the chain, skipping shuffles of the other half and looking
21833 /// through shuffles which switch halves trying to find a shuffle of the same
21834 /// pair of dwords.
21835 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21836                                         SelectionDAG &DAG,
21837                                         TargetLowering::DAGCombinerInfo &DCI) {
21838   assert(
21839       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21840       "Called with something other than an x86 128-bit half shuffle!");
21841   SDLoc DL(N);
21842   unsigned CombineOpcode = N.getOpcode();
21843
21844   // Walk up a single-use chain looking for a combinable shuffle.
21845   SDValue V = N.getOperand(0);
21846   for (; V.hasOneUse(); V = V.getOperand(0)) {
21847     switch (V.getOpcode()) {
21848     default:
21849       return false; // Nothing combined!
21850
21851     case ISD::BITCAST:
21852       // Skip bitcasts as we always know the type for the target specific
21853       // instructions.
21854       continue;
21855
21856     case X86ISD::PSHUFLW:
21857     case X86ISD::PSHUFHW:
21858       if (V.getOpcode() == CombineOpcode)
21859         break;
21860
21861       // Other-half shuffles are no-ops.
21862       continue;
21863     }
21864     // Break out of the loop if we break out of the switch.
21865     break;
21866   }
21867
21868   if (!V.hasOneUse())
21869     // We fell out of the loop without finding a viable combining instruction.
21870     return false;
21871
21872   // Combine away the bottom node as its shuffle will be accumulated into
21873   // a preceding shuffle.
21874   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21875
21876   // Record the old value.
21877   SDValue Old = V;
21878
21879   // Merge this node's mask and our incoming mask (adjusted to account for all
21880   // the pshufd instructions encountered).
21881   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21882   for (int &M : Mask)
21883     M = VMask[M];
21884   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21885                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21886
21887   // Check that the shuffles didn't cancel each other out. If not, we need to
21888   // combine to the new one.
21889   if (Old != V)
21890     // Replace the combinable shuffle with the combined one, updating all users
21891     // so that we re-evaluate the chain here.
21892     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21893
21894   return true;
21895 }
21896
21897 /// \brief Try to combine x86 target specific shuffles.
21898 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21899                                            TargetLowering::DAGCombinerInfo &DCI,
21900                                            const X86Subtarget *Subtarget) {
21901   SDLoc DL(N);
21902   MVT VT = N.getSimpleValueType();
21903   SmallVector<int, 4> Mask;
21904
21905   switch (N.getOpcode()) {
21906   case X86ISD::PSHUFD:
21907   case X86ISD::PSHUFLW:
21908   case X86ISD::PSHUFHW:
21909     Mask = getPSHUFShuffleMask(N);
21910     assert(Mask.size() == 4);
21911     break;
21912   default:
21913     return SDValue();
21914   }
21915
21916   // Nuke no-op shuffles that show up after combining.
21917   if (isNoopShuffleMask(Mask))
21918     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21919
21920   // Look for simplifications involving one or two shuffle instructions.
21921   SDValue V = N.getOperand(0);
21922   switch (N.getOpcode()) {
21923   default:
21924     break;
21925   case X86ISD::PSHUFLW:
21926   case X86ISD::PSHUFHW:
21927     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21928
21929     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21930       return SDValue(); // We combined away this shuffle, so we're done.
21931
21932     // See if this reduces to a PSHUFD which is no more expensive and can
21933     // combine with more operations. Note that it has to at least flip the
21934     // dwords as otherwise it would have been removed as a no-op.
21935     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21936       int DMask[] = {0, 1, 2, 3};
21937       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21938       DMask[DOffset + 0] = DOffset + 1;
21939       DMask[DOffset + 1] = DOffset + 0;
21940       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21941       V = DAG.getBitcast(DVT, V);
21942       DCI.AddToWorklist(V.getNode());
21943       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21944                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21945       DCI.AddToWorklist(V.getNode());
21946       return DAG.getBitcast(VT, V);
21947     }
21948
21949     // Look for shuffle patterns which can be implemented as a single unpack.
21950     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21951     // only works when we have a PSHUFD followed by two half-shuffles.
21952     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21953         (V.getOpcode() == X86ISD::PSHUFLW ||
21954          V.getOpcode() == X86ISD::PSHUFHW) &&
21955         V.getOpcode() != N.getOpcode() &&
21956         V.hasOneUse()) {
21957       SDValue D = V.getOperand(0);
21958       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21959         D = D.getOperand(0);
21960       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21961         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21962         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21963         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21964         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21965         int WordMask[8];
21966         for (int i = 0; i < 4; ++i) {
21967           WordMask[i + NOffset] = Mask[i] + NOffset;
21968           WordMask[i + VOffset] = VMask[i] + VOffset;
21969         }
21970         // Map the word mask through the DWord mask.
21971         int MappedMask[8];
21972         for (int i = 0; i < 8; ++i)
21973           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21974         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21975             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21976           // We can replace all three shuffles with an unpack.
21977           V = DAG.getBitcast(VT, D.getOperand(0));
21978           DCI.AddToWorklist(V.getNode());
21979           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21980                                                 : X86ISD::UNPCKH,
21981                              DL, VT, V, V);
21982         }
21983       }
21984     }
21985
21986     break;
21987
21988   case X86ISD::PSHUFD:
21989     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21990       return NewN;
21991
21992     break;
21993   }
21994
21995   return SDValue();
21996 }
21997
21998 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21999 ///
22000 /// We combine this directly on the abstract vector shuffle nodes so it is
22001 /// easier to generically match. We also insert dummy vector shuffle nodes for
22002 /// the operands which explicitly discard the lanes which are unused by this
22003 /// operation to try to flow through the rest of the combiner the fact that
22004 /// they're unused.
22005 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22006   SDLoc DL(N);
22007   EVT VT = N->getValueType(0);
22008
22009   // We only handle target-independent shuffles.
22010   // FIXME: It would be easy and harmless to use the target shuffle mask
22011   // extraction tool to support more.
22012   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22013     return SDValue();
22014
22015   auto *SVN = cast<ShuffleVectorSDNode>(N);
22016   ArrayRef<int> Mask = SVN->getMask();
22017   SDValue V1 = N->getOperand(0);
22018   SDValue V2 = N->getOperand(1);
22019
22020   // We require the first shuffle operand to be the SUB node, and the second to
22021   // be the ADD node.
22022   // FIXME: We should support the commuted patterns.
22023   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22024     return SDValue();
22025
22026   // If there are other uses of these operations we can't fold them.
22027   if (!V1->hasOneUse() || !V2->hasOneUse())
22028     return SDValue();
22029
22030   // Ensure that both operations have the same operands. Note that we can
22031   // commute the FADD operands.
22032   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22033   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22034       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22035     return SDValue();
22036
22037   // We're looking for blends between FADD and FSUB nodes. We insist on these
22038   // nodes being lined up in a specific expected pattern.
22039   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22040         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22041         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22042     return SDValue();
22043
22044   // Only specific types are legal at this point, assert so we notice if and
22045   // when these change.
22046   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22047           VT == MVT::v4f64) &&
22048          "Unknown vector type encountered!");
22049
22050   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22051 }
22052
22053 /// PerformShuffleCombine - Performs several different shuffle combines.
22054 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22055                                      TargetLowering::DAGCombinerInfo &DCI,
22056                                      const X86Subtarget *Subtarget) {
22057   SDLoc dl(N);
22058   SDValue N0 = N->getOperand(0);
22059   SDValue N1 = N->getOperand(1);
22060   EVT VT = N->getValueType(0);
22061
22062   // Don't create instructions with illegal types after legalize types has run.
22063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22064   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22065     return SDValue();
22066
22067   // If we have legalized the vector types, look for blends of FADD and FSUB
22068   // nodes that we can fuse into an ADDSUB node.
22069   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22070     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22071       return AddSub;
22072
22073   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22074   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22075       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22076     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22077
22078   // During Type Legalization, when promoting illegal vector types,
22079   // the backend might introduce new shuffle dag nodes and bitcasts.
22080   //
22081   // This code performs the following transformation:
22082   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22083   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22084   //
22085   // We do this only if both the bitcast and the BINOP dag nodes have
22086   // one use. Also, perform this transformation only if the new binary
22087   // operation is legal. This is to avoid introducing dag nodes that
22088   // potentially need to be further expanded (or custom lowered) into a
22089   // less optimal sequence of dag nodes.
22090   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22091       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22092       N0.getOpcode() == ISD::BITCAST) {
22093     SDValue BC0 = N0.getOperand(0);
22094     EVT SVT = BC0.getValueType();
22095     unsigned Opcode = BC0.getOpcode();
22096     unsigned NumElts = VT.getVectorNumElements();
22097
22098     if (BC0.hasOneUse() && SVT.isVector() &&
22099         SVT.getVectorNumElements() * 2 == NumElts &&
22100         TLI.isOperationLegal(Opcode, VT)) {
22101       bool CanFold = false;
22102       switch (Opcode) {
22103       default : break;
22104       case ISD::ADD :
22105       case ISD::FADD :
22106       case ISD::SUB :
22107       case ISD::FSUB :
22108       case ISD::MUL :
22109       case ISD::FMUL :
22110         CanFold = true;
22111       }
22112
22113       unsigned SVTNumElts = SVT.getVectorNumElements();
22114       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22115       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22116         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22117       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22118         CanFold = SVOp->getMaskElt(i) < 0;
22119
22120       if (CanFold) {
22121         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22122         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22123         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22124         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22125       }
22126     }
22127   }
22128
22129   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22130   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22131   // consecutive, non-overlapping, and in the right order.
22132   SmallVector<SDValue, 16> Elts;
22133   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22134     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22135
22136   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22137     return LD;
22138
22139   if (isTargetShuffle(N->getOpcode())) {
22140     SDValue Shuffle =
22141         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22142     if (Shuffle.getNode())
22143       return Shuffle;
22144
22145     // Try recursively combining arbitrary sequences of x86 shuffle
22146     // instructions into higher-order shuffles. We do this after combining
22147     // specific PSHUF instruction sequences into their minimal form so that we
22148     // can evaluate how many specialized shuffle instructions are involved in
22149     // a particular chain.
22150     SmallVector<int, 1> NonceMask; // Just a placeholder.
22151     NonceMask.push_back(0);
22152     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22153                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22154                                       DCI, Subtarget))
22155       return SDValue(); // This routine will use CombineTo to replace N.
22156   }
22157
22158   return SDValue();
22159 }
22160
22161 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22162 /// specific shuffle of a load can be folded into a single element load.
22163 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22164 /// shuffles have been custom lowered so we need to handle those here.
22165 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22166                                          TargetLowering::DAGCombinerInfo &DCI) {
22167   if (DCI.isBeforeLegalizeOps())
22168     return SDValue();
22169
22170   SDValue InVec = N->getOperand(0);
22171   SDValue EltNo = N->getOperand(1);
22172
22173   if (!isa<ConstantSDNode>(EltNo))
22174     return SDValue();
22175
22176   EVT OriginalVT = InVec.getValueType();
22177
22178   if (InVec.getOpcode() == ISD::BITCAST) {
22179     // Don't duplicate a load with other uses.
22180     if (!InVec.hasOneUse())
22181       return SDValue();
22182     EVT BCVT = InVec.getOperand(0).getValueType();
22183     if (!BCVT.isVector() ||
22184         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22185       return SDValue();
22186     InVec = InVec.getOperand(0);
22187   }
22188
22189   EVT CurrentVT = InVec.getValueType();
22190
22191   if (!isTargetShuffle(InVec.getOpcode()))
22192     return SDValue();
22193
22194   // Don't duplicate a load with other uses.
22195   if (!InVec.hasOneUse())
22196     return SDValue();
22197
22198   SmallVector<int, 16> ShuffleMask;
22199   bool UnaryShuffle;
22200   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22201                             ShuffleMask, UnaryShuffle))
22202     return SDValue();
22203
22204   // Select the input vector, guarding against out of range extract vector.
22205   unsigned NumElems = CurrentVT.getVectorNumElements();
22206   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22207   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22208   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22209                                          : InVec.getOperand(1);
22210
22211   // If inputs to shuffle are the same for both ops, then allow 2 uses
22212   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22213                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22214
22215   if (LdNode.getOpcode() == ISD::BITCAST) {
22216     // Don't duplicate a load with other uses.
22217     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22218       return SDValue();
22219
22220     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22221     LdNode = LdNode.getOperand(0);
22222   }
22223
22224   if (!ISD::isNormalLoad(LdNode.getNode()))
22225     return SDValue();
22226
22227   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22228
22229   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22230     return SDValue();
22231
22232   EVT EltVT = N->getValueType(0);
22233   // If there's a bitcast before the shuffle, check if the load type and
22234   // alignment is valid.
22235   unsigned Align = LN0->getAlignment();
22236   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22237   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22238       EltVT.getTypeForEVT(*DAG.getContext()));
22239
22240   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22241     return SDValue();
22242
22243   // All checks match so transform back to vector_shuffle so that DAG combiner
22244   // can finish the job
22245   SDLoc dl(N);
22246
22247   // Create shuffle node taking into account the case that its a unary shuffle
22248   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22249                                    : InVec.getOperand(1);
22250   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22251                                  InVec.getOperand(0), Shuffle,
22252                                  &ShuffleMask[0]);
22253   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22254   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22255                      EltNo);
22256 }
22257
22258 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22259 /// special and don't usually play with other vector types, it's better to
22260 /// handle them early to be sure we emit efficient code by avoiding
22261 /// store-load conversions.
22262 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22263   if (N->getValueType(0) != MVT::x86mmx ||
22264       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22265       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22266     return SDValue();
22267
22268   SDValue V = N->getOperand(0);
22269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22270   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22271     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22272                        N->getValueType(0), V.getOperand(0));
22273
22274   return SDValue();
22275 }
22276
22277 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22278 /// generation and convert it from being a bunch of shuffles and extracts
22279 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22280 /// storing the value and loading scalars back, while for x64 we should
22281 /// use 64-bit extracts and shifts.
22282 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22283                                          TargetLowering::DAGCombinerInfo &DCI) {
22284   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22285     return NewOp;
22286
22287   SDValue InputVector = N->getOperand(0);
22288   SDLoc dl(InputVector);
22289   // Detect mmx to i32 conversion through a v2i32 elt extract.
22290   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22291       N->getValueType(0) == MVT::i32 &&
22292       InputVector.getValueType() == MVT::v2i32) {
22293
22294     // The bitcast source is a direct mmx result.
22295     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22296     if (MMXSrc.getValueType() == MVT::x86mmx)
22297       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22298                          N->getValueType(0),
22299                          InputVector.getNode()->getOperand(0));
22300
22301     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22302     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22303     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22304         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22305         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22306         MMXSrcOp.getValueType() == MVT::v1i64 &&
22307         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22308       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22309                          N->getValueType(0),
22310                          MMXSrcOp.getOperand(0));
22311   }
22312
22313   EVT VT = N->getValueType(0);
22314
22315   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22316       InputVector.getOpcode() == ISD::BITCAST &&
22317       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22318     uint64_t ExtractedElt =
22319           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22320     uint64_t InputValue =
22321           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22322     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22323     return DAG.getConstant(Res, dl, MVT::i1);
22324   }
22325   // Only operate on vectors of 4 elements, where the alternative shuffling
22326   // gets to be more expensive.
22327   if (InputVector.getValueType() != MVT::v4i32)
22328     return SDValue();
22329
22330   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22331   // single use which is a sign-extend or zero-extend, and all elements are
22332   // used.
22333   SmallVector<SDNode *, 4> Uses;
22334   unsigned ExtractedElements = 0;
22335   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22336        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22337     if (UI.getUse().getResNo() != InputVector.getResNo())
22338       return SDValue();
22339
22340     SDNode *Extract = *UI;
22341     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22342       return SDValue();
22343
22344     if (Extract->getValueType(0) != MVT::i32)
22345       return SDValue();
22346     if (!Extract->hasOneUse())
22347       return SDValue();
22348     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22349         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22350       return SDValue();
22351     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22352       return SDValue();
22353
22354     // Record which element was extracted.
22355     ExtractedElements |=
22356       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22357
22358     Uses.push_back(Extract);
22359   }
22360
22361   // If not all the elements were used, this may not be worthwhile.
22362   if (ExtractedElements != 15)
22363     return SDValue();
22364
22365   // Ok, we've now decided to do the transformation.
22366   // If 64-bit shifts are legal, use the extract-shift sequence,
22367   // otherwise bounce the vector off the cache.
22368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22369   SDValue Vals[4];
22370
22371   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22372     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22373     auto &DL = DAG.getDataLayout();
22374     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22375     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22376       DAG.getConstant(0, dl, VecIdxTy));
22377     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22378       DAG.getConstant(1, dl, VecIdxTy));
22379
22380     SDValue ShAmt = DAG.getConstant(
22381         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22382     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22383     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22384       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22385     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22386     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22387       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22388   } else {
22389     // Store the value to a temporary stack slot.
22390     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22391     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22392       MachinePointerInfo(), false, false, 0);
22393
22394     EVT ElementType = InputVector.getValueType().getVectorElementType();
22395     unsigned EltSize = ElementType.getSizeInBits() / 8;
22396
22397     // Replace each use (extract) with a load of the appropriate element.
22398     for (unsigned i = 0; i < 4; ++i) {
22399       uint64_t Offset = EltSize * i;
22400       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22401       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22402
22403       SDValue ScalarAddr =
22404           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22405
22406       // Load the scalar.
22407       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22408                             ScalarAddr, MachinePointerInfo(),
22409                             false, false, false, 0);
22410
22411     }
22412   }
22413
22414   // Replace the extracts
22415   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22416     UE = Uses.end(); UI != UE; ++UI) {
22417     SDNode *Extract = *UI;
22418
22419     SDValue Idx = Extract->getOperand(1);
22420     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22421     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22422   }
22423
22424   // The replacement was made in place; don't return anything.
22425   return SDValue();
22426 }
22427
22428 static SDValue
22429 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22430                                       const X86Subtarget *Subtarget) {
22431   SDLoc dl(N);
22432   SDValue Cond = N->getOperand(0);
22433   SDValue LHS = N->getOperand(1);
22434   SDValue RHS = N->getOperand(2);
22435
22436   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22437     SDValue CondSrc = Cond->getOperand(0);
22438     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22439       Cond = CondSrc->getOperand(0);
22440   }
22441
22442   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22443     return SDValue();
22444
22445   // A vselect where all conditions and data are constants can be optimized into
22446   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22447   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22448       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22449     return SDValue();
22450
22451   unsigned MaskValue = 0;
22452   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22453     return SDValue();
22454
22455   MVT VT = N->getSimpleValueType(0);
22456   unsigned NumElems = VT.getVectorNumElements();
22457   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22458   for (unsigned i = 0; i < NumElems; ++i) {
22459     // Be sure we emit undef where we can.
22460     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22461       ShuffleMask[i] = -1;
22462     else
22463       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22464   }
22465
22466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22467   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22468     return SDValue();
22469   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22470 }
22471
22472 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22473 /// nodes.
22474 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22475                                     TargetLowering::DAGCombinerInfo &DCI,
22476                                     const X86Subtarget *Subtarget) {
22477   SDLoc DL(N);
22478   SDValue Cond = N->getOperand(0);
22479   // Get the LHS/RHS of the select.
22480   SDValue LHS = N->getOperand(1);
22481   SDValue RHS = N->getOperand(2);
22482   EVT VT = LHS.getValueType();
22483   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22484
22485   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22486   // instructions match the semantics of the common C idiom x<y?x:y but not
22487   // x<=y?x:y, because of how they handle negative zero (which can be
22488   // ignored in unsafe-math mode).
22489   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22490   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22491       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22492       (Subtarget->hasSSE2() ||
22493        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22494     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22495
22496     unsigned Opcode = 0;
22497     // Check for x CC y ? x : y.
22498     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22499         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22500       switch (CC) {
22501       default: break;
22502       case ISD::SETULT:
22503         // Converting this to a min would handle NaNs incorrectly, and swapping
22504         // the operands would cause it to handle comparisons between positive
22505         // and negative zero incorrectly.
22506         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22507           if (!DAG.getTarget().Options.UnsafeFPMath &&
22508               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22509             break;
22510           std::swap(LHS, RHS);
22511         }
22512         Opcode = X86ISD::FMIN;
22513         break;
22514       case ISD::SETOLE:
22515         // Converting this to a min would handle comparisons between positive
22516         // and negative zero incorrectly.
22517         if (!DAG.getTarget().Options.UnsafeFPMath &&
22518             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22519           break;
22520         Opcode = X86ISD::FMIN;
22521         break;
22522       case ISD::SETULE:
22523         // Converting this to a min would handle both negative zeros and NaNs
22524         // incorrectly, but we can swap the operands to fix both.
22525         std::swap(LHS, RHS);
22526       case ISD::SETOLT:
22527       case ISD::SETLT:
22528       case ISD::SETLE:
22529         Opcode = X86ISD::FMIN;
22530         break;
22531
22532       case ISD::SETOGE:
22533         // Converting this to a max would handle comparisons between positive
22534         // and negative zero incorrectly.
22535         if (!DAG.getTarget().Options.UnsafeFPMath &&
22536             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22537           break;
22538         Opcode = X86ISD::FMAX;
22539         break;
22540       case ISD::SETUGT:
22541         // Converting this to a max would handle NaNs incorrectly, and swapping
22542         // the operands would cause it to handle comparisons between positive
22543         // and negative zero incorrectly.
22544         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22545           if (!DAG.getTarget().Options.UnsafeFPMath &&
22546               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22547             break;
22548           std::swap(LHS, RHS);
22549         }
22550         Opcode = X86ISD::FMAX;
22551         break;
22552       case ISD::SETUGE:
22553         // Converting this to a max would handle both negative zeros and NaNs
22554         // incorrectly, but we can swap the operands to fix both.
22555         std::swap(LHS, RHS);
22556       case ISD::SETOGT:
22557       case ISD::SETGT:
22558       case ISD::SETGE:
22559         Opcode = X86ISD::FMAX;
22560         break;
22561       }
22562     // Check for x CC y ? y : x -- a min/max with reversed arms.
22563     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22564                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22565       switch (CC) {
22566       default: break;
22567       case ISD::SETOGE:
22568         // Converting this to a min would handle comparisons between positive
22569         // and negative zero incorrectly, and swapping the operands would
22570         // cause it to handle NaNs incorrectly.
22571         if (!DAG.getTarget().Options.UnsafeFPMath &&
22572             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22573           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22574             break;
22575           std::swap(LHS, RHS);
22576         }
22577         Opcode = X86ISD::FMIN;
22578         break;
22579       case ISD::SETUGT:
22580         // Converting this to a min would handle NaNs incorrectly.
22581         if (!DAG.getTarget().Options.UnsafeFPMath &&
22582             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22583           break;
22584         Opcode = X86ISD::FMIN;
22585         break;
22586       case ISD::SETUGE:
22587         // Converting this to a min would handle both negative zeros and NaNs
22588         // incorrectly, but we can swap the operands to fix both.
22589         std::swap(LHS, RHS);
22590       case ISD::SETOGT:
22591       case ISD::SETGT:
22592       case ISD::SETGE:
22593         Opcode = X86ISD::FMIN;
22594         break;
22595
22596       case ISD::SETULT:
22597         // Converting this to a max would handle NaNs incorrectly.
22598         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22599           break;
22600         Opcode = X86ISD::FMAX;
22601         break;
22602       case ISD::SETOLE:
22603         // Converting this to a max would handle comparisons between positive
22604         // and negative zero incorrectly, and swapping the operands would
22605         // cause it to handle NaNs incorrectly.
22606         if (!DAG.getTarget().Options.UnsafeFPMath &&
22607             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22608           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22609             break;
22610           std::swap(LHS, RHS);
22611         }
22612         Opcode = X86ISD::FMAX;
22613         break;
22614       case ISD::SETULE:
22615         // Converting this to a max would handle both negative zeros and NaNs
22616         // incorrectly, but we can swap the operands to fix both.
22617         std::swap(LHS, RHS);
22618       case ISD::SETOLT:
22619       case ISD::SETLT:
22620       case ISD::SETLE:
22621         Opcode = X86ISD::FMAX;
22622         break;
22623       }
22624     }
22625
22626     if (Opcode)
22627       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22628   }
22629
22630   EVT CondVT = Cond.getValueType();
22631   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22632       CondVT.getVectorElementType() == MVT::i1) {
22633     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22634     // lowering on KNL. In this case we convert it to
22635     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22636     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22637     // Since SKX these selects have a proper lowering.
22638     EVT OpVT = LHS.getValueType();
22639     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22640         (OpVT.getVectorElementType() == MVT::i8 ||
22641          OpVT.getVectorElementType() == MVT::i16) &&
22642         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22643       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22644       DCI.AddToWorklist(Cond.getNode());
22645       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22646     }
22647   }
22648   // If this is a select between two integer constants, try to do some
22649   // optimizations.
22650   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22651     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22652       // Don't do this for crazy integer types.
22653       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22654         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22655         // so that TrueC (the true value) is larger than FalseC.
22656         bool NeedsCondInvert = false;
22657
22658         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22659             // Efficiently invertible.
22660             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22661              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22662               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22663           NeedsCondInvert = true;
22664           std::swap(TrueC, FalseC);
22665         }
22666
22667         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22668         if (FalseC->getAPIntValue() == 0 &&
22669             TrueC->getAPIntValue().isPowerOf2()) {
22670           if (NeedsCondInvert) // Invert the condition if needed.
22671             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22672                                DAG.getConstant(1, DL, Cond.getValueType()));
22673
22674           // Zero extend the condition if needed.
22675           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22676
22677           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22678           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22679                              DAG.getConstant(ShAmt, DL, MVT::i8));
22680         }
22681
22682         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22683         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22684           if (NeedsCondInvert) // Invert the condition if needed.
22685             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22686                                DAG.getConstant(1, DL, Cond.getValueType()));
22687
22688           // Zero extend the condition if needed.
22689           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22690                              FalseC->getValueType(0), Cond);
22691           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22692                              SDValue(FalseC, 0));
22693         }
22694
22695         // Optimize cases that will turn into an LEA instruction.  This requires
22696         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22697         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22698           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22699           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22700
22701           bool isFastMultiplier = false;
22702           if (Diff < 10) {
22703             switch ((unsigned char)Diff) {
22704               default: break;
22705               case 1:  // result = add base, cond
22706               case 2:  // result = lea base(    , cond*2)
22707               case 3:  // result = lea base(cond, cond*2)
22708               case 4:  // result = lea base(    , cond*4)
22709               case 5:  // result = lea base(cond, cond*4)
22710               case 8:  // result = lea base(    , cond*8)
22711               case 9:  // result = lea base(cond, cond*8)
22712                 isFastMultiplier = true;
22713                 break;
22714             }
22715           }
22716
22717           if (isFastMultiplier) {
22718             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22719             if (NeedsCondInvert) // Invert the condition if needed.
22720               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22721                                  DAG.getConstant(1, DL, Cond.getValueType()));
22722
22723             // Zero extend the condition if needed.
22724             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22725                                Cond);
22726             // Scale the condition by the difference.
22727             if (Diff != 1)
22728               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22729                                  DAG.getConstant(Diff, DL,
22730                                                  Cond.getValueType()));
22731
22732             // Add the base if non-zero.
22733             if (FalseC->getAPIntValue() != 0)
22734               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22735                                  SDValue(FalseC, 0));
22736             return Cond;
22737           }
22738         }
22739       }
22740   }
22741
22742   // Canonicalize max and min:
22743   // (x > y) ? x : y -> (x >= y) ? x : y
22744   // (x < y) ? x : y -> (x <= y) ? x : y
22745   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22746   // the need for an extra compare
22747   // against zero. e.g.
22748   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22749   // subl   %esi, %edi
22750   // testl  %edi, %edi
22751   // movl   $0, %eax
22752   // cmovgl %edi, %eax
22753   // =>
22754   // xorl   %eax, %eax
22755   // subl   %esi, $edi
22756   // cmovsl %eax, %edi
22757   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22758       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22759       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22760     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22761     switch (CC) {
22762     default: break;
22763     case ISD::SETLT:
22764     case ISD::SETGT: {
22765       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22766       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22767                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22768       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22769     }
22770     }
22771   }
22772
22773   // Early exit check
22774   if (!TLI.isTypeLegal(VT))
22775     return SDValue();
22776
22777   // Match VSELECTs into subs with unsigned saturation.
22778   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22779       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22780       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22781        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22782     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22783
22784     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22785     // left side invert the predicate to simplify logic below.
22786     SDValue Other;
22787     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22788       Other = RHS;
22789       CC = ISD::getSetCCInverse(CC, true);
22790     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22791       Other = LHS;
22792     }
22793
22794     if (Other.getNode() && Other->getNumOperands() == 2 &&
22795         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22796       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22797       SDValue CondRHS = Cond->getOperand(1);
22798
22799       // Look for a general sub with unsigned saturation first.
22800       // x >= y ? x-y : 0 --> subus x, y
22801       // x >  y ? x-y : 0 --> subus x, y
22802       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22803           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22804         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22805
22806       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22807         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22808           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22809             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22810               // If the RHS is a constant we have to reverse the const
22811               // canonicalization.
22812               // x > C-1 ? x+-C : 0 --> subus x, C
22813               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22814                   CondRHSConst->getAPIntValue() ==
22815                       (-OpRHSConst->getAPIntValue() - 1))
22816                 return DAG.getNode(
22817                     X86ISD::SUBUS, DL, VT, OpLHS,
22818                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22819
22820           // Another special case: If C was a sign bit, the sub has been
22821           // canonicalized into a xor.
22822           // FIXME: Would it be better to use computeKnownBits to determine
22823           //        whether it's safe to decanonicalize the xor?
22824           // x s< 0 ? x^C : 0 --> subus x, C
22825           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22826               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22827               OpRHSConst->getAPIntValue().isSignBit())
22828             // Note that we have to rebuild the RHS constant here to ensure we
22829             // don't rely on particular values of undef lanes.
22830             return DAG.getNode(
22831                 X86ISD::SUBUS, DL, VT, OpLHS,
22832                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22833         }
22834     }
22835   }
22836
22837   // Simplify vector selection if condition value type matches vselect
22838   // operand type
22839   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22840     assert(Cond.getValueType().isVector() &&
22841            "vector select expects a vector selector!");
22842
22843     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22844     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22845
22846     // Try invert the condition if true value is not all 1s and false value
22847     // is not all 0s.
22848     if (!TValIsAllOnes && !FValIsAllZeros &&
22849         // Check if the selector will be produced by CMPP*/PCMP*
22850         Cond.getOpcode() == ISD::SETCC &&
22851         // Check if SETCC has already been promoted
22852         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22853             CondVT) {
22854       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22855       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22856
22857       if (TValIsAllZeros || FValIsAllOnes) {
22858         SDValue CC = Cond.getOperand(2);
22859         ISD::CondCode NewCC =
22860           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22861                                Cond.getOperand(0).getValueType().isInteger());
22862         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22863         std::swap(LHS, RHS);
22864         TValIsAllOnes = FValIsAllOnes;
22865         FValIsAllZeros = TValIsAllZeros;
22866       }
22867     }
22868
22869     if (TValIsAllOnes || FValIsAllZeros) {
22870       SDValue Ret;
22871
22872       if (TValIsAllOnes && FValIsAllZeros)
22873         Ret = Cond;
22874       else if (TValIsAllOnes)
22875         Ret =
22876             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22877       else if (FValIsAllZeros)
22878         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22879                           DAG.getBitcast(CondVT, LHS));
22880
22881       return DAG.getBitcast(VT, Ret);
22882     }
22883   }
22884
22885   // We should generate an X86ISD::BLENDI from a vselect if its argument
22886   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22887   // constants. This specific pattern gets generated when we split a
22888   // selector for a 512 bit vector in a machine without AVX512 (but with
22889   // 256-bit vectors), during legalization:
22890   //
22891   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22892   //
22893   // Iff we find this pattern and the build_vectors are built from
22894   // constants, we translate the vselect into a shuffle_vector that we
22895   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22896   if ((N->getOpcode() == ISD::VSELECT ||
22897        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22898       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22899     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22900     if (Shuffle.getNode())
22901       return Shuffle;
22902   }
22903
22904   // If this is a *dynamic* select (non-constant condition) and we can match
22905   // this node with one of the variable blend instructions, restructure the
22906   // condition so that the blends can use the high bit of each element and use
22907   // SimplifyDemandedBits to simplify the condition operand.
22908   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22909       !DCI.isBeforeLegalize() &&
22910       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22911     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22912
22913     // Don't optimize vector selects that map to mask-registers.
22914     if (BitWidth == 1)
22915       return SDValue();
22916
22917     // We can only handle the cases where VSELECT is directly legal on the
22918     // subtarget. We custom lower VSELECT nodes with constant conditions and
22919     // this makes it hard to see whether a dynamic VSELECT will correctly
22920     // lower, so we both check the operation's status and explicitly handle the
22921     // cases where a *dynamic* blend will fail even though a constant-condition
22922     // blend could be custom lowered.
22923     // FIXME: We should find a better way to handle this class of problems.
22924     // Potentially, we should combine constant-condition vselect nodes
22925     // pre-legalization into shuffles and not mark as many types as custom
22926     // lowered.
22927     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22928       return SDValue();
22929     // FIXME: We don't support i16-element blends currently. We could and
22930     // should support them by making *all* the bits in the condition be set
22931     // rather than just the high bit and using an i8-element blend.
22932     if (VT.getScalarType() == MVT::i16)
22933       return SDValue();
22934     // Dynamic blending was only available from SSE4.1 onward.
22935     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22936       return SDValue();
22937     // Byte blends are only available in AVX2
22938     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22939         !Subtarget->hasAVX2())
22940       return SDValue();
22941
22942     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22943     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22944
22945     APInt KnownZero, KnownOne;
22946     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22947                                           DCI.isBeforeLegalizeOps());
22948     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22949         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22950                                  TLO)) {
22951       // If we changed the computation somewhere in the DAG, this change
22952       // will affect all users of Cond.
22953       // Make sure it is fine and update all the nodes so that we do not
22954       // use the generic VSELECT anymore. Otherwise, we may perform
22955       // wrong optimizations as we messed up with the actual expectation
22956       // for the vector boolean values.
22957       if (Cond != TLO.Old) {
22958         // Check all uses of that condition operand to check whether it will be
22959         // consumed by non-BLEND instructions, which may depend on all bits are
22960         // set properly.
22961         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22962              I != E; ++I)
22963           if (I->getOpcode() != ISD::VSELECT)
22964             // TODO: Add other opcodes eventually lowered into BLEND.
22965             return SDValue();
22966
22967         // Update all the users of the condition, before committing the change,
22968         // so that the VSELECT optimizations that expect the correct vector
22969         // boolean value will not be triggered.
22970         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22971              I != E; ++I)
22972           DAG.ReplaceAllUsesOfValueWith(
22973               SDValue(*I, 0),
22974               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22975                           Cond, I->getOperand(1), I->getOperand(2)));
22976         DCI.CommitTargetLoweringOpt(TLO);
22977         return SDValue();
22978       }
22979       // At this point, only Cond is changed. Change the condition
22980       // just for N to keep the opportunity to optimize all other
22981       // users their own way.
22982       DAG.ReplaceAllUsesOfValueWith(
22983           SDValue(N, 0),
22984           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22985                       TLO.New, N->getOperand(1), N->getOperand(2)));
22986       return SDValue();
22987     }
22988   }
22989
22990   return SDValue();
22991 }
22992
22993 // Check whether a boolean test is testing a boolean value generated by
22994 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22995 // code.
22996 //
22997 // Simplify the following patterns:
22998 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22999 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23000 // to (Op EFLAGS Cond)
23001 //
23002 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23003 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23004 // to (Op EFLAGS !Cond)
23005 //
23006 // where Op could be BRCOND or CMOV.
23007 //
23008 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23009   // Quit if not CMP and SUB with its value result used.
23010   if (Cmp.getOpcode() != X86ISD::CMP &&
23011       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23012       return SDValue();
23013
23014   // Quit if not used as a boolean value.
23015   if (CC != X86::COND_E && CC != X86::COND_NE)
23016     return SDValue();
23017
23018   // Check CMP operands. One of them should be 0 or 1 and the other should be
23019   // an SetCC or extended from it.
23020   SDValue Op1 = Cmp.getOperand(0);
23021   SDValue Op2 = Cmp.getOperand(1);
23022
23023   SDValue SetCC;
23024   const ConstantSDNode* C = nullptr;
23025   bool needOppositeCond = (CC == X86::COND_E);
23026   bool checkAgainstTrue = false; // Is it a comparison against 1?
23027
23028   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23029     SetCC = Op2;
23030   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23031     SetCC = Op1;
23032   else // Quit if all operands are not constants.
23033     return SDValue();
23034
23035   if (C->getZExtValue() == 1) {
23036     needOppositeCond = !needOppositeCond;
23037     checkAgainstTrue = true;
23038   } else if (C->getZExtValue() != 0)
23039     // Quit if the constant is neither 0 or 1.
23040     return SDValue();
23041
23042   bool truncatedToBoolWithAnd = false;
23043   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23044   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23045          SetCC.getOpcode() == ISD::TRUNCATE ||
23046          SetCC.getOpcode() == ISD::AND) {
23047     if (SetCC.getOpcode() == ISD::AND) {
23048       int OpIdx = -1;
23049       ConstantSDNode *CS;
23050       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23051           CS->getZExtValue() == 1)
23052         OpIdx = 1;
23053       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23054           CS->getZExtValue() == 1)
23055         OpIdx = 0;
23056       if (OpIdx == -1)
23057         break;
23058       SetCC = SetCC.getOperand(OpIdx);
23059       truncatedToBoolWithAnd = true;
23060     } else
23061       SetCC = SetCC.getOperand(0);
23062   }
23063
23064   switch (SetCC.getOpcode()) {
23065   case X86ISD::SETCC_CARRY:
23066     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23067     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23068     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23069     // truncated to i1 using 'and'.
23070     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23071       break;
23072     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23073            "Invalid use of SETCC_CARRY!");
23074     // FALL THROUGH
23075   case X86ISD::SETCC:
23076     // Set the condition code or opposite one if necessary.
23077     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23078     if (needOppositeCond)
23079       CC = X86::GetOppositeBranchCondition(CC);
23080     return SetCC.getOperand(1);
23081   case X86ISD::CMOV: {
23082     // Check whether false/true value has canonical one, i.e. 0 or 1.
23083     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23084     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23085     // Quit if true value is not a constant.
23086     if (!TVal)
23087       return SDValue();
23088     // Quit if false value is not a constant.
23089     if (!FVal) {
23090       SDValue Op = SetCC.getOperand(0);
23091       // Skip 'zext' or 'trunc' node.
23092       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23093           Op.getOpcode() == ISD::TRUNCATE)
23094         Op = Op.getOperand(0);
23095       // A special case for rdrand/rdseed, where 0 is set if false cond is
23096       // found.
23097       if ((Op.getOpcode() != X86ISD::RDRAND &&
23098            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23099         return SDValue();
23100     }
23101     // Quit if false value is not the constant 0 or 1.
23102     bool FValIsFalse = true;
23103     if (FVal && FVal->getZExtValue() != 0) {
23104       if (FVal->getZExtValue() != 1)
23105         return SDValue();
23106       // If FVal is 1, opposite cond is needed.
23107       needOppositeCond = !needOppositeCond;
23108       FValIsFalse = false;
23109     }
23110     // Quit if TVal is not the constant opposite of FVal.
23111     if (FValIsFalse && TVal->getZExtValue() != 1)
23112       return SDValue();
23113     if (!FValIsFalse && TVal->getZExtValue() != 0)
23114       return SDValue();
23115     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23116     if (needOppositeCond)
23117       CC = X86::GetOppositeBranchCondition(CC);
23118     return SetCC.getOperand(3);
23119   }
23120   }
23121
23122   return SDValue();
23123 }
23124
23125 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23126 /// Match:
23127 ///   (X86or (X86setcc) (X86setcc))
23128 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23129 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23130                                            X86::CondCode &CC1, SDValue &Flags,
23131                                            bool &isAnd) {
23132   if (Cond->getOpcode() == X86ISD::CMP) {
23133     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23134     if (!CondOp1C || !CondOp1C->isNullValue())
23135       return false;
23136
23137     Cond = Cond->getOperand(0);
23138   }
23139
23140   isAnd = false;
23141
23142   SDValue SetCC0, SetCC1;
23143   switch (Cond->getOpcode()) {
23144   default: return false;
23145   case ISD::AND:
23146   case X86ISD::AND:
23147     isAnd = true;
23148     // fallthru
23149   case ISD::OR:
23150   case X86ISD::OR:
23151     SetCC0 = Cond->getOperand(0);
23152     SetCC1 = Cond->getOperand(1);
23153     break;
23154   };
23155
23156   // Make sure we have SETCC nodes, using the same flags value.
23157   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23158       SetCC1.getOpcode() != X86ISD::SETCC ||
23159       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23160     return false;
23161
23162   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23163   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23164   Flags = SetCC0->getOperand(1);
23165   return true;
23166 }
23167
23168 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23169 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23170                                   TargetLowering::DAGCombinerInfo &DCI,
23171                                   const X86Subtarget *Subtarget) {
23172   SDLoc DL(N);
23173
23174   // If the flag operand isn't dead, don't touch this CMOV.
23175   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23176     return SDValue();
23177
23178   SDValue FalseOp = N->getOperand(0);
23179   SDValue TrueOp = N->getOperand(1);
23180   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23181   SDValue Cond = N->getOperand(3);
23182
23183   if (CC == X86::COND_E || CC == X86::COND_NE) {
23184     switch (Cond.getOpcode()) {
23185     default: break;
23186     case X86ISD::BSR:
23187     case X86ISD::BSF:
23188       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23189       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23190         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23191     }
23192   }
23193
23194   SDValue Flags;
23195
23196   Flags = checkBoolTestSetCCCombine(Cond, CC);
23197   if (Flags.getNode() &&
23198       // Extra check as FCMOV only supports a subset of X86 cond.
23199       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23200     SDValue Ops[] = { FalseOp, TrueOp,
23201                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23202     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23203   }
23204
23205   // If this is a select between two integer constants, try to do some
23206   // optimizations.  Note that the operands are ordered the opposite of SELECT
23207   // operands.
23208   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23209     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23210       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23211       // larger than FalseC (the false value).
23212       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23213         CC = X86::GetOppositeBranchCondition(CC);
23214         std::swap(TrueC, FalseC);
23215         std::swap(TrueOp, FalseOp);
23216       }
23217
23218       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23219       // This is efficient for any integer data type (including i8/i16) and
23220       // shift amount.
23221       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23222         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23223                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23224
23225         // Zero extend the condition if needed.
23226         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23227
23228         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23229         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23230                            DAG.getConstant(ShAmt, DL, MVT::i8));
23231         if (N->getNumValues() == 2)  // Dead flag value?
23232           return DCI.CombineTo(N, Cond, SDValue());
23233         return Cond;
23234       }
23235
23236       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23237       // for any integer data type, including i8/i16.
23238       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23239         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23240                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23241
23242         // Zero extend the condition if needed.
23243         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23244                            FalseC->getValueType(0), Cond);
23245         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23246                            SDValue(FalseC, 0));
23247
23248         if (N->getNumValues() == 2)  // Dead flag value?
23249           return DCI.CombineTo(N, Cond, SDValue());
23250         return Cond;
23251       }
23252
23253       // Optimize cases that will turn into an LEA instruction.  This requires
23254       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23255       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23256         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23257         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23258
23259         bool isFastMultiplier = false;
23260         if (Diff < 10) {
23261           switch ((unsigned char)Diff) {
23262           default: break;
23263           case 1:  // result = add base, cond
23264           case 2:  // result = lea base(    , cond*2)
23265           case 3:  // result = lea base(cond, cond*2)
23266           case 4:  // result = lea base(    , cond*4)
23267           case 5:  // result = lea base(cond, cond*4)
23268           case 8:  // result = lea base(    , cond*8)
23269           case 9:  // result = lea base(cond, cond*8)
23270             isFastMultiplier = true;
23271             break;
23272           }
23273         }
23274
23275         if (isFastMultiplier) {
23276           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23277           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23278                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23279           // Zero extend the condition if needed.
23280           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23281                              Cond);
23282           // Scale the condition by the difference.
23283           if (Diff != 1)
23284             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23285                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23286
23287           // Add the base if non-zero.
23288           if (FalseC->getAPIntValue() != 0)
23289             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23290                                SDValue(FalseC, 0));
23291           if (N->getNumValues() == 2)  // Dead flag value?
23292             return DCI.CombineTo(N, Cond, SDValue());
23293           return Cond;
23294         }
23295       }
23296     }
23297   }
23298
23299   // Handle these cases:
23300   //   (select (x != c), e, c) -> select (x != c), e, x),
23301   //   (select (x == c), c, e) -> select (x == c), x, e)
23302   // where the c is an integer constant, and the "select" is the combination
23303   // of CMOV and CMP.
23304   //
23305   // The rationale for this change is that the conditional-move from a constant
23306   // needs two instructions, however, conditional-move from a register needs
23307   // only one instruction.
23308   //
23309   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23310   //  some instruction-combining opportunities. This opt needs to be
23311   //  postponed as late as possible.
23312   //
23313   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23314     // the DCI.xxxx conditions are provided to postpone the optimization as
23315     // late as possible.
23316
23317     ConstantSDNode *CmpAgainst = nullptr;
23318     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23319         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23320         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23321
23322       if (CC == X86::COND_NE &&
23323           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23324         CC = X86::GetOppositeBranchCondition(CC);
23325         std::swap(TrueOp, FalseOp);
23326       }
23327
23328       if (CC == X86::COND_E &&
23329           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23330         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23331                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23332         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23333       }
23334     }
23335   }
23336
23337   // Fold and/or of setcc's to double CMOV:
23338   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23339   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23340   //
23341   // This combine lets us generate:
23342   //   cmovcc1 (jcc1 if we don't have CMOV)
23343   //   cmovcc2 (same)
23344   // instead of:
23345   //   setcc1
23346   //   setcc2
23347   //   and/or
23348   //   cmovne (jne if we don't have CMOV)
23349   // When we can't use the CMOV instruction, it might increase branch
23350   // mispredicts.
23351   // When we can use CMOV, or when there is no mispredict, this improves
23352   // throughput and reduces register pressure.
23353   //
23354   if (CC == X86::COND_NE) {
23355     SDValue Flags;
23356     X86::CondCode CC0, CC1;
23357     bool isAndSetCC;
23358     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23359       if (isAndSetCC) {
23360         std::swap(FalseOp, TrueOp);
23361         CC0 = X86::GetOppositeBranchCondition(CC0);
23362         CC1 = X86::GetOppositeBranchCondition(CC1);
23363       }
23364
23365       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23366         Flags};
23367       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23368       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23369       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23370       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23371       return CMOV;
23372     }
23373   }
23374
23375   return SDValue();
23376 }
23377
23378 /// PerformMulCombine - Optimize a single multiply with constant into two
23379 /// in order to implement it with two cheaper instructions, e.g.
23380 /// LEA + SHL, LEA + LEA.
23381 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23382                                  TargetLowering::DAGCombinerInfo &DCI) {
23383   // An imul is usually smaller than the alternative sequence.
23384   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23385     return SDValue();
23386
23387   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23388     return SDValue();
23389
23390   EVT VT = N->getValueType(0);
23391   if (VT != MVT::i64 && VT != MVT::i32)
23392     return SDValue();
23393
23394   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23395   if (!C)
23396     return SDValue();
23397   uint64_t MulAmt = C->getZExtValue();
23398   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23399     return SDValue();
23400
23401   uint64_t MulAmt1 = 0;
23402   uint64_t MulAmt2 = 0;
23403   if ((MulAmt % 9) == 0) {
23404     MulAmt1 = 9;
23405     MulAmt2 = MulAmt / 9;
23406   } else if ((MulAmt % 5) == 0) {
23407     MulAmt1 = 5;
23408     MulAmt2 = MulAmt / 5;
23409   } else if ((MulAmt % 3) == 0) {
23410     MulAmt1 = 3;
23411     MulAmt2 = MulAmt / 3;
23412   }
23413   if (MulAmt2 &&
23414       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23415     SDLoc DL(N);
23416
23417     if (isPowerOf2_64(MulAmt2) &&
23418         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23419       // If second multiplifer is pow2, issue it first. We want the multiply by
23420       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23421       // is an add.
23422       std::swap(MulAmt1, MulAmt2);
23423
23424     SDValue NewMul;
23425     if (isPowerOf2_64(MulAmt1))
23426       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23427                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23428     else
23429       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23430                            DAG.getConstant(MulAmt1, DL, VT));
23431
23432     if (isPowerOf2_64(MulAmt2))
23433       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23434                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23435     else
23436       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23437                            DAG.getConstant(MulAmt2, DL, VT));
23438
23439     // Do not add new nodes to DAG combiner worklist.
23440     DCI.CombineTo(N, NewMul, false);
23441   }
23442   return SDValue();
23443 }
23444
23445 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23446   SDValue N0 = N->getOperand(0);
23447   SDValue N1 = N->getOperand(1);
23448   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23449   EVT VT = N0.getValueType();
23450
23451   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23452   // since the result of setcc_c is all zero's or all ones.
23453   if (VT.isInteger() && !VT.isVector() &&
23454       N1C && N0.getOpcode() == ISD::AND &&
23455       N0.getOperand(1).getOpcode() == ISD::Constant) {
23456     SDValue N00 = N0.getOperand(0);
23457     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23458     APInt ShAmt = N1C->getAPIntValue();
23459     Mask = Mask.shl(ShAmt);
23460     bool MaskOK = false;
23461     // We can handle cases concerning bit-widening nodes containing setcc_c if
23462     // we carefully interrogate the mask to make sure we are semantics
23463     // preserving.
23464     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23465     // of the underlying setcc_c operation if the setcc_c was zero extended.
23466     // Consider the following example:
23467     //   zext(setcc_c)                 -> i32 0x0000FFFF
23468     //   c1                            -> i32 0x0000FFFF
23469     //   c2                            -> i32 0x00000001
23470     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23471     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23472     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23473       MaskOK = true;
23474     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23475                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23476       MaskOK = true;
23477     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23478                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23479                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23480       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23481     }
23482     if (MaskOK && Mask != 0) {
23483       SDLoc DL(N);
23484       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23485     }
23486   }
23487
23488   // Hardware support for vector shifts is sparse which makes us scalarize the
23489   // vector operations in many cases. Also, on sandybridge ADD is faster than
23490   // shl.
23491   // (shl V, 1) -> add V,V
23492   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23493     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23494       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23495       // We shift all of the values by one. In many cases we do not have
23496       // hardware support for this operation. This is better expressed as an ADD
23497       // of two values.
23498       if (N1SplatC->getAPIntValue() == 1)
23499         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23500     }
23501
23502   return SDValue();
23503 }
23504
23505 /// \brief Returns a vector of 0s if the node in input is a vector logical
23506 /// shift by a constant amount which is known to be bigger than or equal
23507 /// to the vector element size in bits.
23508 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23509                                       const X86Subtarget *Subtarget) {
23510   EVT VT = N->getValueType(0);
23511
23512   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23513       (!Subtarget->hasInt256() ||
23514        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23515     return SDValue();
23516
23517   SDValue Amt = N->getOperand(1);
23518   SDLoc DL(N);
23519   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23520     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23521       APInt ShiftAmt = AmtSplat->getAPIntValue();
23522       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23523
23524       // SSE2/AVX2 logical shifts always return a vector of 0s
23525       // if the shift amount is bigger than or equal to
23526       // the element size. The constant shift amount will be
23527       // encoded as a 8-bit immediate.
23528       if (ShiftAmt.trunc(8).uge(MaxAmount))
23529         return getZeroVector(VT, Subtarget, DAG, DL);
23530     }
23531
23532   return SDValue();
23533 }
23534
23535 /// PerformShiftCombine - Combine shifts.
23536 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23537                                    TargetLowering::DAGCombinerInfo &DCI,
23538                                    const X86Subtarget *Subtarget) {
23539   if (N->getOpcode() == ISD::SHL)
23540     if (SDValue V = PerformSHLCombine(N, DAG))
23541       return V;
23542
23543   // Try to fold this logical shift into a zero vector.
23544   if (N->getOpcode() != ISD::SRA)
23545     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23546       return V;
23547
23548   return SDValue();
23549 }
23550
23551 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23552 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23553 // and friends.  Likewise for OR -> CMPNEQSS.
23554 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23555                             TargetLowering::DAGCombinerInfo &DCI,
23556                             const X86Subtarget *Subtarget) {
23557   unsigned opcode;
23558
23559   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23560   // we're requiring SSE2 for both.
23561   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23562     SDValue N0 = N->getOperand(0);
23563     SDValue N1 = N->getOperand(1);
23564     SDValue CMP0 = N0->getOperand(1);
23565     SDValue CMP1 = N1->getOperand(1);
23566     SDLoc DL(N);
23567
23568     // The SETCCs should both refer to the same CMP.
23569     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23570       return SDValue();
23571
23572     SDValue CMP00 = CMP0->getOperand(0);
23573     SDValue CMP01 = CMP0->getOperand(1);
23574     EVT     VT    = CMP00.getValueType();
23575
23576     if (VT == MVT::f32 || VT == MVT::f64) {
23577       bool ExpectingFlags = false;
23578       // Check for any users that want flags:
23579       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23580            !ExpectingFlags && UI != UE; ++UI)
23581         switch (UI->getOpcode()) {
23582         default:
23583         case ISD::BR_CC:
23584         case ISD::BRCOND:
23585         case ISD::SELECT:
23586           ExpectingFlags = true;
23587           break;
23588         case ISD::CopyToReg:
23589         case ISD::SIGN_EXTEND:
23590         case ISD::ZERO_EXTEND:
23591         case ISD::ANY_EXTEND:
23592           break;
23593         }
23594
23595       if (!ExpectingFlags) {
23596         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23597         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23598
23599         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23600           X86::CondCode tmp = cc0;
23601           cc0 = cc1;
23602           cc1 = tmp;
23603         }
23604
23605         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23606             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23607           // FIXME: need symbolic constants for these magic numbers.
23608           // See X86ATTInstPrinter.cpp:printSSECC().
23609           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23610           if (Subtarget->hasAVX512()) {
23611             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23612                                          CMP01,
23613                                          DAG.getConstant(x86cc, DL, MVT::i8));
23614             if (N->getValueType(0) != MVT::i1)
23615               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23616                                  FSetCC);
23617             return FSetCC;
23618           }
23619           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23620                                               CMP00.getValueType(), CMP00, CMP01,
23621                                               DAG.getConstant(x86cc, DL,
23622                                                               MVT::i8));
23623
23624           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23625           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23626
23627           if (is64BitFP && !Subtarget->is64Bit()) {
23628             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23629             // 64-bit integer, since that's not a legal type. Since
23630             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23631             // bits, but can do this little dance to extract the lowest 32 bits
23632             // and work with those going forward.
23633             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23634                                            OnesOrZeroesF);
23635             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23636             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23637                                         Vector32, DAG.getIntPtrConstant(0, DL));
23638             IntVT = MVT::i32;
23639           }
23640
23641           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23642           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23643                                       DAG.getConstant(1, DL, IntVT));
23644           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23645                                               ANDed);
23646           return OneBitOfTruth;
23647         }
23648       }
23649     }
23650   }
23651   return SDValue();
23652 }
23653
23654 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23655 /// so it can be folded inside ANDNP.
23656 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23657   EVT VT = N->getValueType(0);
23658
23659   // Match direct AllOnes for 128 and 256-bit vectors
23660   if (ISD::isBuildVectorAllOnes(N))
23661     return true;
23662
23663   // Look through a bit convert.
23664   if (N->getOpcode() == ISD::BITCAST)
23665     N = N->getOperand(0).getNode();
23666
23667   // Sometimes the operand may come from a insert_subvector building a 256-bit
23668   // allones vector
23669   if (VT.is256BitVector() &&
23670       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23671     SDValue V1 = N->getOperand(0);
23672     SDValue V2 = N->getOperand(1);
23673
23674     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23675         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23676         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23677         ISD::isBuildVectorAllOnes(V2.getNode()))
23678       return true;
23679   }
23680
23681   return false;
23682 }
23683
23684 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23685 // register. In most cases we actually compare or select YMM-sized registers
23686 // and mixing the two types creates horrible code. This method optimizes
23687 // some of the transition sequences.
23688 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23689                                  TargetLowering::DAGCombinerInfo &DCI,
23690                                  const X86Subtarget *Subtarget) {
23691   EVT VT = N->getValueType(0);
23692   if (!VT.is256BitVector())
23693     return SDValue();
23694
23695   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23696           N->getOpcode() == ISD::ZERO_EXTEND ||
23697           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23698
23699   SDValue Narrow = N->getOperand(0);
23700   EVT NarrowVT = Narrow->getValueType(0);
23701   if (!NarrowVT.is128BitVector())
23702     return SDValue();
23703
23704   if (Narrow->getOpcode() != ISD::XOR &&
23705       Narrow->getOpcode() != ISD::AND &&
23706       Narrow->getOpcode() != ISD::OR)
23707     return SDValue();
23708
23709   SDValue N0  = Narrow->getOperand(0);
23710   SDValue N1  = Narrow->getOperand(1);
23711   SDLoc DL(Narrow);
23712
23713   // The Left side has to be a trunc.
23714   if (N0.getOpcode() != ISD::TRUNCATE)
23715     return SDValue();
23716
23717   // The type of the truncated inputs.
23718   EVT WideVT = N0->getOperand(0)->getValueType(0);
23719   if (WideVT != VT)
23720     return SDValue();
23721
23722   // The right side has to be a 'trunc' or a constant vector.
23723   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23724   ConstantSDNode *RHSConstSplat = nullptr;
23725   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23726     RHSConstSplat = RHSBV->getConstantSplatNode();
23727   if (!RHSTrunc && !RHSConstSplat)
23728     return SDValue();
23729
23730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23731
23732   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23733     return SDValue();
23734
23735   // Set N0 and N1 to hold the inputs to the new wide operation.
23736   N0 = N0->getOperand(0);
23737   if (RHSConstSplat) {
23738     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23739                      SDValue(RHSConstSplat, 0));
23740     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23741     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23742   } else if (RHSTrunc) {
23743     N1 = N1->getOperand(0);
23744   }
23745
23746   // Generate the wide operation.
23747   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23748   unsigned Opcode = N->getOpcode();
23749   switch (Opcode) {
23750   case ISD::ANY_EXTEND:
23751     return Op;
23752   case ISD::ZERO_EXTEND: {
23753     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23754     APInt Mask = APInt::getAllOnesValue(InBits);
23755     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23756     return DAG.getNode(ISD::AND, DL, VT,
23757                        Op, DAG.getConstant(Mask, DL, VT));
23758   }
23759   case ISD::SIGN_EXTEND:
23760     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23761                        Op, DAG.getValueType(NarrowVT));
23762   default:
23763     llvm_unreachable("Unexpected opcode");
23764   }
23765 }
23766
23767 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23768                                  TargetLowering::DAGCombinerInfo &DCI,
23769                                  const X86Subtarget *Subtarget) {
23770   SDValue N0 = N->getOperand(0);
23771   SDValue N1 = N->getOperand(1);
23772   SDLoc DL(N);
23773
23774   // A vector zext_in_reg may be represented as a shuffle,
23775   // feeding into a bitcast (this represents anyext) feeding into
23776   // an and with a mask.
23777   // We'd like to try to combine that into a shuffle with zero
23778   // plus a bitcast, removing the and.
23779   if (N0.getOpcode() != ISD::BITCAST ||
23780       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23781     return SDValue();
23782
23783   // The other side of the AND should be a splat of 2^C, where C
23784   // is the number of bits in the source type.
23785   if (N1.getOpcode() == ISD::BITCAST)
23786     N1 = N1.getOperand(0);
23787   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23788     return SDValue();
23789   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23790
23791   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23792   EVT SrcType = Shuffle->getValueType(0);
23793
23794   // We expect a single-source shuffle
23795   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23796     return SDValue();
23797
23798   unsigned SrcSize = SrcType.getScalarSizeInBits();
23799
23800   APInt SplatValue, SplatUndef;
23801   unsigned SplatBitSize;
23802   bool HasAnyUndefs;
23803   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23804                                 SplatBitSize, HasAnyUndefs))
23805     return SDValue();
23806
23807   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23808   // Make sure the splat matches the mask we expect
23809   if (SplatBitSize > ResSize ||
23810       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23811     return SDValue();
23812
23813   // Make sure the input and output size make sense
23814   if (SrcSize >= ResSize || ResSize % SrcSize)
23815     return SDValue();
23816
23817   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23818   // The number of u's between each two values depends on the ratio between
23819   // the source and dest type.
23820   unsigned ZextRatio = ResSize / SrcSize;
23821   bool IsZext = true;
23822   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23823     if (i % ZextRatio) {
23824       if (Shuffle->getMaskElt(i) > 0) {
23825         // Expected undef
23826         IsZext = false;
23827         break;
23828       }
23829     } else {
23830       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23831         // Expected element number
23832         IsZext = false;
23833         break;
23834       }
23835     }
23836   }
23837
23838   if (!IsZext)
23839     return SDValue();
23840
23841   // Ok, perform the transformation - replace the shuffle with
23842   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23843   // (instead of undef) where the k elements come from the zero vector.
23844   SmallVector<int, 8> Mask;
23845   unsigned NumElems = SrcType.getVectorNumElements();
23846   for (unsigned i = 0; i < NumElems; ++i)
23847     if (i % ZextRatio)
23848       Mask.push_back(NumElems);
23849     else
23850       Mask.push_back(i / ZextRatio);
23851
23852   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23853     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23854   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23855 }
23856
23857 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23858                                  TargetLowering::DAGCombinerInfo &DCI,
23859                                  const X86Subtarget *Subtarget) {
23860   if (DCI.isBeforeLegalizeOps())
23861     return SDValue();
23862
23863   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23864     return Zext;
23865
23866   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23867     return R;
23868
23869   EVT VT = N->getValueType(0);
23870   SDValue N0 = N->getOperand(0);
23871   SDValue N1 = N->getOperand(1);
23872   SDLoc DL(N);
23873
23874   // Create BEXTR instructions
23875   // BEXTR is ((X >> imm) & (2**size-1))
23876   if (VT == MVT::i32 || VT == MVT::i64) {
23877     // Check for BEXTR.
23878     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23879         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23880       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23881       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23882       if (MaskNode && ShiftNode) {
23883         uint64_t Mask = MaskNode->getZExtValue();
23884         uint64_t Shift = ShiftNode->getZExtValue();
23885         if (isMask_64(Mask)) {
23886           uint64_t MaskSize = countPopulation(Mask);
23887           if (Shift + MaskSize <= VT.getSizeInBits())
23888             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23889                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23890                                                VT));
23891         }
23892       }
23893     } // BEXTR
23894
23895     return SDValue();
23896   }
23897
23898   // Want to form ANDNP nodes:
23899   // 1) In the hopes of then easily combining them with OR and AND nodes
23900   //    to form PBLEND/PSIGN.
23901   // 2) To match ANDN packed intrinsics
23902   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23903     return SDValue();
23904
23905   // Check LHS for vnot
23906   if (N0.getOpcode() == ISD::XOR &&
23907       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23908       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23909     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23910
23911   // Check RHS for vnot
23912   if (N1.getOpcode() == ISD::XOR &&
23913       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23914       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23915     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23916
23917   return SDValue();
23918 }
23919
23920 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23921                                 TargetLowering::DAGCombinerInfo &DCI,
23922                                 const X86Subtarget *Subtarget) {
23923   if (DCI.isBeforeLegalizeOps())
23924     return SDValue();
23925
23926   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23927     return R;
23928
23929   SDValue N0 = N->getOperand(0);
23930   SDValue N1 = N->getOperand(1);
23931   EVT VT = N->getValueType(0);
23932
23933   // look for psign/blend
23934   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23935     if (!Subtarget->hasSSSE3() ||
23936         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23937       return SDValue();
23938
23939     // Canonicalize pandn to RHS
23940     if (N0.getOpcode() == X86ISD::ANDNP)
23941       std::swap(N0, N1);
23942     // or (and (m, y), (pandn m, x))
23943     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23944       SDValue Mask = N1.getOperand(0);
23945       SDValue X    = N1.getOperand(1);
23946       SDValue Y;
23947       if (N0.getOperand(0) == Mask)
23948         Y = N0.getOperand(1);
23949       if (N0.getOperand(1) == Mask)
23950         Y = N0.getOperand(0);
23951
23952       // Check to see if the mask appeared in both the AND and ANDNP and
23953       if (!Y.getNode())
23954         return SDValue();
23955
23956       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23957       // Look through mask bitcast.
23958       if (Mask.getOpcode() == ISD::BITCAST)
23959         Mask = Mask.getOperand(0);
23960       if (X.getOpcode() == ISD::BITCAST)
23961         X = X.getOperand(0);
23962       if (Y.getOpcode() == ISD::BITCAST)
23963         Y = Y.getOperand(0);
23964
23965       EVT MaskVT = Mask.getValueType();
23966
23967       // Validate that the Mask operand is a vector sra node.
23968       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23969       // there is no psrai.b
23970       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23971       unsigned SraAmt = ~0;
23972       if (Mask.getOpcode() == ISD::SRA) {
23973         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23974           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23975             SraAmt = AmtConst->getZExtValue();
23976       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23977         SDValue SraC = Mask.getOperand(1);
23978         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23979       }
23980       if ((SraAmt + 1) != EltBits)
23981         return SDValue();
23982
23983       SDLoc DL(N);
23984
23985       // Now we know we at least have a plendvb with the mask val.  See if
23986       // we can form a psignb/w/d.
23987       // psign = x.type == y.type == mask.type && y = sub(0, x);
23988       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23989           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23990           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23991         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23992                "Unsupported VT for PSIGN");
23993         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23994         return DAG.getBitcast(VT, Mask);
23995       }
23996       // PBLENDVB only available on SSE 4.1
23997       if (!Subtarget->hasSSE41())
23998         return SDValue();
23999
24000       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24001
24002       X = DAG.getBitcast(BlendVT, X);
24003       Y = DAG.getBitcast(BlendVT, Y);
24004       Mask = DAG.getBitcast(BlendVT, Mask);
24005       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24006       return DAG.getBitcast(VT, Mask);
24007     }
24008   }
24009
24010   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24011     return SDValue();
24012
24013   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24014   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24015
24016   // SHLD/SHRD instructions have lower register pressure, but on some
24017   // platforms they have higher latency than the equivalent
24018   // series of shifts/or that would otherwise be generated.
24019   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24020   // have higher latencies and we are not optimizing for size.
24021   if (!OptForSize && Subtarget->isSHLDSlow())
24022     return SDValue();
24023
24024   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24025     std::swap(N0, N1);
24026   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24027     return SDValue();
24028   if (!N0.hasOneUse() || !N1.hasOneUse())
24029     return SDValue();
24030
24031   SDValue ShAmt0 = N0.getOperand(1);
24032   if (ShAmt0.getValueType() != MVT::i8)
24033     return SDValue();
24034   SDValue ShAmt1 = N1.getOperand(1);
24035   if (ShAmt1.getValueType() != MVT::i8)
24036     return SDValue();
24037   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24038     ShAmt0 = ShAmt0.getOperand(0);
24039   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24040     ShAmt1 = ShAmt1.getOperand(0);
24041
24042   SDLoc DL(N);
24043   unsigned Opc = X86ISD::SHLD;
24044   SDValue Op0 = N0.getOperand(0);
24045   SDValue Op1 = N1.getOperand(0);
24046   if (ShAmt0.getOpcode() == ISD::SUB) {
24047     Opc = X86ISD::SHRD;
24048     std::swap(Op0, Op1);
24049     std::swap(ShAmt0, ShAmt1);
24050   }
24051
24052   unsigned Bits = VT.getSizeInBits();
24053   if (ShAmt1.getOpcode() == ISD::SUB) {
24054     SDValue Sum = ShAmt1.getOperand(0);
24055     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24056       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24057       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24058         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24059       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24060         return DAG.getNode(Opc, DL, VT,
24061                            Op0, Op1,
24062                            DAG.getNode(ISD::TRUNCATE, DL,
24063                                        MVT::i8, ShAmt0));
24064     }
24065   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24066     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24067     if (ShAmt0C &&
24068         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24069       return DAG.getNode(Opc, DL, VT,
24070                          N0.getOperand(0), N1.getOperand(0),
24071                          DAG.getNode(ISD::TRUNCATE, DL,
24072                                        MVT::i8, ShAmt0));
24073   }
24074
24075   return SDValue();
24076 }
24077
24078 // Generate NEG and CMOV for integer abs.
24079 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24080   EVT VT = N->getValueType(0);
24081
24082   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24083   // 8-bit integer abs to NEG and CMOV.
24084   if (VT.isInteger() && VT.getSizeInBits() == 8)
24085     return SDValue();
24086
24087   SDValue N0 = N->getOperand(0);
24088   SDValue N1 = N->getOperand(1);
24089   SDLoc DL(N);
24090
24091   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24092   // and change it to SUB and CMOV.
24093   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24094       N0.getOpcode() == ISD::ADD &&
24095       N0.getOperand(1) == N1 &&
24096       N1.getOpcode() == ISD::SRA &&
24097       N1.getOperand(0) == N0.getOperand(0))
24098     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24099       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24100         // Generate SUB & CMOV.
24101         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24102                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24103
24104         SDValue Ops[] = { N0.getOperand(0), Neg,
24105                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24106                           SDValue(Neg.getNode(), 1) };
24107         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24108       }
24109   return SDValue();
24110 }
24111
24112 // Try to turn tests against the signbit in the form of:
24113 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24114 // into:
24115 //   SETGT(X, -1)
24116 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24117   // This is only worth doing if the output type is i8.
24118   if (N->getValueType(0) != MVT::i8)
24119     return SDValue();
24120
24121   SDValue N0 = N->getOperand(0);
24122   SDValue N1 = N->getOperand(1);
24123
24124   // We should be performing an xor against a truncated shift.
24125   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24126     return SDValue();
24127
24128   // Make sure we are performing an xor against one.
24129   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24130     return SDValue();
24131
24132   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24133   SDValue Shift = N0.getOperand(0);
24134   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24135     return SDValue();
24136
24137   // Make sure we are truncating from one of i16, i32 or i64.
24138   EVT ShiftTy = Shift.getValueType();
24139   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24140     return SDValue();
24141
24142   // Make sure the shift amount extracts the sign bit.
24143   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24144       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24145     return SDValue();
24146
24147   // Create a greater-than comparison against -1.
24148   // N.B. Using SETGE against 0 works but we want a canonical looking
24149   // comparison, using SETGT matches up with what TranslateX86CC.
24150   SDLoc DL(N);
24151   SDValue ShiftOp = Shift.getOperand(0);
24152   EVT ShiftOpTy = ShiftOp.getValueType();
24153   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24154                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24155   return Cond;
24156 }
24157
24158 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24159                                  TargetLowering::DAGCombinerInfo &DCI,
24160                                  const X86Subtarget *Subtarget) {
24161   if (DCI.isBeforeLegalizeOps())
24162     return SDValue();
24163
24164   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24165     return RV;
24166
24167   if (Subtarget->hasCMov())
24168     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24169       return RV;
24170
24171   return SDValue();
24172 }
24173
24174 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24175 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24176                                   TargetLowering::DAGCombinerInfo &DCI,
24177                                   const X86Subtarget *Subtarget) {
24178   LoadSDNode *Ld = cast<LoadSDNode>(N);
24179   EVT RegVT = Ld->getValueType(0);
24180   EVT MemVT = Ld->getMemoryVT();
24181   SDLoc dl(Ld);
24182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24183
24184   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24185   // into two 16-byte operations.
24186   ISD::LoadExtType Ext = Ld->getExtensionType();
24187   bool Fast;
24188   unsigned AddressSpace = Ld->getAddressSpace();
24189   unsigned Alignment = Ld->getAlignment();
24190   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24191       Ext == ISD::NON_EXTLOAD &&
24192       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24193                              AddressSpace, Alignment, &Fast) && !Fast) {
24194     unsigned NumElems = RegVT.getVectorNumElements();
24195     if (NumElems < 2)
24196       return SDValue();
24197
24198     SDValue Ptr = Ld->getBasePtr();
24199     SDValue Increment =
24200         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24201
24202     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24203                                   NumElems/2);
24204     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24205                                 Ld->getPointerInfo(), Ld->isVolatile(),
24206                                 Ld->isNonTemporal(), Ld->isInvariant(),
24207                                 Alignment);
24208     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24209     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24210                                 Ld->getPointerInfo(), Ld->isVolatile(),
24211                                 Ld->isNonTemporal(), Ld->isInvariant(),
24212                                 std::min(16U, Alignment));
24213     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24214                              Load1.getValue(1),
24215                              Load2.getValue(1));
24216
24217     SDValue NewVec = DAG.getUNDEF(RegVT);
24218     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24219     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24220     return DCI.CombineTo(N, NewVec, TF, true);
24221   }
24222
24223   return SDValue();
24224 }
24225
24226 /// PerformMLOADCombine - Resolve extending loads
24227 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24228                                    TargetLowering::DAGCombinerInfo &DCI,
24229                                    const X86Subtarget *Subtarget) {
24230   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24231   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24232     return SDValue();
24233
24234   EVT VT = Mld->getValueType(0);
24235   unsigned NumElems = VT.getVectorNumElements();
24236   EVT LdVT = Mld->getMemoryVT();
24237   SDLoc dl(Mld);
24238
24239   assert(LdVT != VT && "Cannot extend to the same type");
24240   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24241   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24242   // From, To sizes and ElemCount must be pow of two
24243   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24244     "Unexpected size for extending masked load");
24245
24246   unsigned SizeRatio  = ToSz / FromSz;
24247   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24248
24249   // Create a type on which we perform the shuffle
24250   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24251           LdVT.getScalarType(), NumElems*SizeRatio);
24252   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24253
24254   // Convert Src0 value
24255   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24256   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24257     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24258     for (unsigned i = 0; i != NumElems; ++i)
24259       ShuffleVec[i] = i * SizeRatio;
24260
24261     // Can't shuffle using an illegal type.
24262     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24263             && "WideVecVT should be legal");
24264     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24265                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24266   }
24267   // Prepare the new mask
24268   SDValue NewMask;
24269   SDValue Mask = Mld->getMask();
24270   if (Mask.getValueType() == VT) {
24271     // Mask and original value have the same type
24272     NewMask = DAG.getBitcast(WideVecVT, Mask);
24273     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24274     for (unsigned i = 0; i != NumElems; ++i)
24275       ShuffleVec[i] = i * SizeRatio;
24276     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24277       ShuffleVec[i] = NumElems*SizeRatio;
24278     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24279                                    DAG.getConstant(0, dl, WideVecVT),
24280                                    &ShuffleVec[0]);
24281   }
24282   else {
24283     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24284     unsigned WidenNumElts = NumElems*SizeRatio;
24285     unsigned MaskNumElts = VT.getVectorNumElements();
24286     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24287                                      WidenNumElts);
24288
24289     unsigned NumConcat = WidenNumElts / MaskNumElts;
24290     SmallVector<SDValue, 16> Ops(NumConcat);
24291     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24292     Ops[0] = Mask;
24293     for (unsigned i = 1; i != NumConcat; ++i)
24294       Ops[i] = ZeroVal;
24295
24296     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24297   }
24298
24299   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24300                                      Mld->getBasePtr(), NewMask, WideSrc0,
24301                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24302                                      ISD::NON_EXTLOAD);
24303   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24304   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24305
24306 }
24307 /// PerformMSTORECombine - Resolve truncating stores
24308 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24309                                     const X86Subtarget *Subtarget) {
24310   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24311   if (!Mst->isTruncatingStore())
24312     return SDValue();
24313
24314   EVT VT = Mst->getValue().getValueType();
24315   unsigned NumElems = VT.getVectorNumElements();
24316   EVT StVT = Mst->getMemoryVT();
24317   SDLoc dl(Mst);
24318
24319   assert(StVT != VT && "Cannot truncate to the same type");
24320   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24321   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24322
24323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24324
24325   // The truncating store is legal in some cases. For example
24326   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24327   // are designated for truncate store.
24328   // In this case we don't need any further transformations.
24329   if (TLI.isTruncStoreLegal(VT, StVT))
24330     return SDValue();
24331
24332   // From, To sizes and ElemCount must be pow of two
24333   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24334     "Unexpected size for truncating masked store");
24335   // We are going to use the original vector elt for storing.
24336   // Accumulated smaller vector elements must be a multiple of the store size.
24337   assert (((NumElems * FromSz) % ToSz) == 0 &&
24338           "Unexpected ratio for truncating masked store");
24339
24340   unsigned SizeRatio  = FromSz / ToSz;
24341   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24342
24343   // Create a type on which we perform the shuffle
24344   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24345           StVT.getScalarType(), NumElems*SizeRatio);
24346
24347   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24348
24349   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24350   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24351   for (unsigned i = 0; i != NumElems; ++i)
24352     ShuffleVec[i] = i * SizeRatio;
24353
24354   // Can't shuffle using an illegal type.
24355   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24356           && "WideVecVT should be legal");
24357
24358   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24359                                         DAG.getUNDEF(WideVecVT),
24360                                         &ShuffleVec[0]);
24361
24362   SDValue NewMask;
24363   SDValue Mask = Mst->getMask();
24364   if (Mask.getValueType() == VT) {
24365     // Mask and original value have the same type
24366     NewMask = DAG.getBitcast(WideVecVT, Mask);
24367     for (unsigned i = 0; i != NumElems; ++i)
24368       ShuffleVec[i] = i * SizeRatio;
24369     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24370       ShuffleVec[i] = NumElems*SizeRatio;
24371     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24372                                    DAG.getConstant(0, dl, WideVecVT),
24373                                    &ShuffleVec[0]);
24374   }
24375   else {
24376     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24377     unsigned WidenNumElts = NumElems*SizeRatio;
24378     unsigned MaskNumElts = VT.getVectorNumElements();
24379     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24380                                      WidenNumElts);
24381
24382     unsigned NumConcat = WidenNumElts / MaskNumElts;
24383     SmallVector<SDValue, 16> Ops(NumConcat);
24384     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24385     Ops[0] = Mask;
24386     for (unsigned i = 1; i != NumConcat; ++i)
24387       Ops[i] = ZeroVal;
24388
24389     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24390   }
24391
24392   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24393                             NewMask, StVT, Mst->getMemOperand(), false);
24394 }
24395 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24396 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24397                                    const X86Subtarget *Subtarget) {
24398   StoreSDNode *St = cast<StoreSDNode>(N);
24399   EVT VT = St->getValue().getValueType();
24400   EVT StVT = St->getMemoryVT();
24401   SDLoc dl(St);
24402   SDValue StoredVal = St->getOperand(1);
24403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24404
24405   // If we are saving a concatenation of two XMM registers and 32-byte stores
24406   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24407   bool Fast;
24408   unsigned AddressSpace = St->getAddressSpace();
24409   unsigned Alignment = St->getAlignment();
24410   if (VT.is256BitVector() && StVT == VT &&
24411       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24412                              AddressSpace, Alignment, &Fast) && !Fast) {
24413     unsigned NumElems = VT.getVectorNumElements();
24414     if (NumElems < 2)
24415       return SDValue();
24416
24417     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24418     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24419
24420     SDValue Stride =
24421         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24422     SDValue Ptr0 = St->getBasePtr();
24423     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24424
24425     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24426                                 St->getPointerInfo(), St->isVolatile(),
24427                                 St->isNonTemporal(), Alignment);
24428     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24429                                 St->getPointerInfo(), St->isVolatile(),
24430                                 St->isNonTemporal(),
24431                                 std::min(16U, Alignment));
24432     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24433   }
24434
24435   // Optimize trunc store (of multiple scalars) to shuffle and store.
24436   // First, pack all of the elements in one place. Next, store to memory
24437   // in fewer chunks.
24438   if (St->isTruncatingStore() && VT.isVector()) {
24439     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24440     unsigned NumElems = VT.getVectorNumElements();
24441     assert(StVT != VT && "Cannot truncate to the same type");
24442     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24443     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24444
24445     // The truncating store is legal in some cases. For example
24446     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24447     // are designated for truncate store.
24448     // In this case we don't need any further transformations.
24449     if (TLI.isTruncStoreLegal(VT, StVT))
24450       return SDValue();
24451
24452     // From, To sizes and ElemCount must be pow of two
24453     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24454     // We are going to use the original vector elt for storing.
24455     // Accumulated smaller vector elements must be a multiple of the store size.
24456     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24457
24458     unsigned SizeRatio  = FromSz / ToSz;
24459
24460     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24461
24462     // Create a type on which we perform the shuffle
24463     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24464             StVT.getScalarType(), NumElems*SizeRatio);
24465
24466     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24467
24468     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24469     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24470     for (unsigned i = 0; i != NumElems; ++i)
24471       ShuffleVec[i] = i * SizeRatio;
24472
24473     // Can't shuffle using an illegal type.
24474     if (!TLI.isTypeLegal(WideVecVT))
24475       return SDValue();
24476
24477     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24478                                          DAG.getUNDEF(WideVecVT),
24479                                          &ShuffleVec[0]);
24480     // At this point all of the data is stored at the bottom of the
24481     // register. We now need to save it to mem.
24482
24483     // Find the largest store unit
24484     MVT StoreType = MVT::i8;
24485     for (MVT Tp : MVT::integer_valuetypes()) {
24486       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24487         StoreType = Tp;
24488     }
24489
24490     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24491     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24492         (64 <= NumElems * ToSz))
24493       StoreType = MVT::f64;
24494
24495     // Bitcast the original vector into a vector of store-size units
24496     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24497             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24498     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24499     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24500     SmallVector<SDValue, 8> Chains;
24501     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24502                                         TLI.getPointerTy(DAG.getDataLayout()));
24503     SDValue Ptr = St->getBasePtr();
24504
24505     // Perform one or more big stores into memory.
24506     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24507       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24508                                    StoreType, ShuffWide,
24509                                    DAG.getIntPtrConstant(i, dl));
24510       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24511                                 St->getPointerInfo(), St->isVolatile(),
24512                                 St->isNonTemporal(), St->getAlignment());
24513       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24514       Chains.push_back(Ch);
24515     }
24516
24517     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24518   }
24519
24520   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24521   // the FP state in cases where an emms may be missing.
24522   // A preferable solution to the general problem is to figure out the right
24523   // places to insert EMMS.  This qualifies as a quick hack.
24524
24525   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24526   if (VT.getSizeInBits() != 64)
24527     return SDValue();
24528
24529   const Function *F = DAG.getMachineFunction().getFunction();
24530   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24531   bool F64IsLegal =
24532       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24533   if ((VT.isVector() ||
24534        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24535       isa<LoadSDNode>(St->getValue()) &&
24536       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24537       St->getChain().hasOneUse() && !St->isVolatile()) {
24538     SDNode* LdVal = St->getValue().getNode();
24539     LoadSDNode *Ld = nullptr;
24540     int TokenFactorIndex = -1;
24541     SmallVector<SDValue, 8> Ops;
24542     SDNode* ChainVal = St->getChain().getNode();
24543     // Must be a store of a load.  We currently handle two cases:  the load
24544     // is a direct child, and it's under an intervening TokenFactor.  It is
24545     // possible to dig deeper under nested TokenFactors.
24546     if (ChainVal == LdVal)
24547       Ld = cast<LoadSDNode>(St->getChain());
24548     else if (St->getValue().hasOneUse() &&
24549              ChainVal->getOpcode() == ISD::TokenFactor) {
24550       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24551         if (ChainVal->getOperand(i).getNode() == LdVal) {
24552           TokenFactorIndex = i;
24553           Ld = cast<LoadSDNode>(St->getValue());
24554         } else
24555           Ops.push_back(ChainVal->getOperand(i));
24556       }
24557     }
24558
24559     if (!Ld || !ISD::isNormalLoad(Ld))
24560       return SDValue();
24561
24562     // If this is not the MMX case, i.e. we are just turning i64 load/store
24563     // into f64 load/store, avoid the transformation if there are multiple
24564     // uses of the loaded value.
24565     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24566       return SDValue();
24567
24568     SDLoc LdDL(Ld);
24569     SDLoc StDL(N);
24570     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24571     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24572     // pair instead.
24573     if (Subtarget->is64Bit() || F64IsLegal) {
24574       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24575       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24576                                   Ld->getPointerInfo(), Ld->isVolatile(),
24577                                   Ld->isNonTemporal(), Ld->isInvariant(),
24578                                   Ld->getAlignment());
24579       SDValue NewChain = NewLd.getValue(1);
24580       if (TokenFactorIndex != -1) {
24581         Ops.push_back(NewChain);
24582         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24583       }
24584       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24585                           St->getPointerInfo(),
24586                           St->isVolatile(), St->isNonTemporal(),
24587                           St->getAlignment());
24588     }
24589
24590     // Otherwise, lower to two pairs of 32-bit loads / stores.
24591     SDValue LoAddr = Ld->getBasePtr();
24592     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24593                                  DAG.getConstant(4, LdDL, MVT::i32));
24594
24595     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24596                                Ld->getPointerInfo(),
24597                                Ld->isVolatile(), Ld->isNonTemporal(),
24598                                Ld->isInvariant(), Ld->getAlignment());
24599     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24600                                Ld->getPointerInfo().getWithOffset(4),
24601                                Ld->isVolatile(), Ld->isNonTemporal(),
24602                                Ld->isInvariant(),
24603                                MinAlign(Ld->getAlignment(), 4));
24604
24605     SDValue NewChain = LoLd.getValue(1);
24606     if (TokenFactorIndex != -1) {
24607       Ops.push_back(LoLd);
24608       Ops.push_back(HiLd);
24609       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24610     }
24611
24612     LoAddr = St->getBasePtr();
24613     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24614                          DAG.getConstant(4, StDL, MVT::i32));
24615
24616     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24617                                 St->getPointerInfo(),
24618                                 St->isVolatile(), St->isNonTemporal(),
24619                                 St->getAlignment());
24620     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24621                                 St->getPointerInfo().getWithOffset(4),
24622                                 St->isVolatile(),
24623                                 St->isNonTemporal(),
24624                                 MinAlign(St->getAlignment(), 4));
24625     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24626   }
24627
24628   // This is similar to the above case, but here we handle a scalar 64-bit
24629   // integer store that is extracted from a vector on a 32-bit target.
24630   // If we have SSE2, then we can treat it like a floating-point double
24631   // to get past legalization. The execution dependencies fixup pass will
24632   // choose the optimal machine instruction for the store if this really is
24633   // an integer or v2f32 rather than an f64.
24634   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24635       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24636     SDValue OldExtract = St->getOperand(1);
24637     SDValue ExtOp0 = OldExtract.getOperand(0);
24638     unsigned VecSize = ExtOp0.getValueSizeInBits();
24639     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24640     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24641     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24642                                      BitCast, OldExtract.getOperand(1));
24643     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24644                         St->getPointerInfo(), St->isVolatile(),
24645                         St->isNonTemporal(), St->getAlignment());
24646   }
24647
24648   return SDValue();
24649 }
24650
24651 /// Return 'true' if this vector operation is "horizontal"
24652 /// and return the operands for the horizontal operation in LHS and RHS.  A
24653 /// horizontal operation performs the binary operation on successive elements
24654 /// of its first operand, then on successive elements of its second operand,
24655 /// returning the resulting values in a vector.  For example, if
24656 ///   A = < float a0, float a1, float a2, float a3 >
24657 /// and
24658 ///   B = < float b0, float b1, float b2, float b3 >
24659 /// then the result of doing a horizontal operation on A and B is
24660 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24661 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24662 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24663 /// set to A, RHS to B, and the routine returns 'true'.
24664 /// Note that the binary operation should have the property that if one of the
24665 /// operands is UNDEF then the result is UNDEF.
24666 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24667   // Look for the following pattern: if
24668   //   A = < float a0, float a1, float a2, float a3 >
24669   //   B = < float b0, float b1, float b2, float b3 >
24670   // and
24671   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24672   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24673   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24674   // which is A horizontal-op B.
24675
24676   // At least one of the operands should be a vector shuffle.
24677   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24678       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24679     return false;
24680
24681   MVT VT = LHS.getSimpleValueType();
24682
24683   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24684          "Unsupported vector type for horizontal add/sub");
24685
24686   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24687   // operate independently on 128-bit lanes.
24688   unsigned NumElts = VT.getVectorNumElements();
24689   unsigned NumLanes = VT.getSizeInBits()/128;
24690   unsigned NumLaneElts = NumElts / NumLanes;
24691   assert((NumLaneElts % 2 == 0) &&
24692          "Vector type should have an even number of elements in each lane");
24693   unsigned HalfLaneElts = NumLaneElts/2;
24694
24695   // View LHS in the form
24696   //   LHS = VECTOR_SHUFFLE A, B, LMask
24697   // If LHS is not a shuffle then pretend it is the shuffle
24698   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24699   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24700   // type VT.
24701   SDValue A, B;
24702   SmallVector<int, 16> LMask(NumElts);
24703   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24704     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24705       A = LHS.getOperand(0);
24706     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24707       B = LHS.getOperand(1);
24708     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24709     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24710   } else {
24711     if (LHS.getOpcode() != ISD::UNDEF)
24712       A = LHS;
24713     for (unsigned i = 0; i != NumElts; ++i)
24714       LMask[i] = i;
24715   }
24716
24717   // Likewise, view RHS in the form
24718   //   RHS = VECTOR_SHUFFLE C, D, RMask
24719   SDValue C, D;
24720   SmallVector<int, 16> RMask(NumElts);
24721   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24722     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24723       C = RHS.getOperand(0);
24724     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24725       D = RHS.getOperand(1);
24726     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24727     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24728   } else {
24729     if (RHS.getOpcode() != ISD::UNDEF)
24730       C = RHS;
24731     for (unsigned i = 0; i != NumElts; ++i)
24732       RMask[i] = i;
24733   }
24734
24735   // Check that the shuffles are both shuffling the same vectors.
24736   if (!(A == C && B == D) && !(A == D && B == C))
24737     return false;
24738
24739   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24740   if (!A.getNode() && !B.getNode())
24741     return false;
24742
24743   // If A and B occur in reverse order in RHS, then "swap" them (which means
24744   // rewriting the mask).
24745   if (A != C)
24746     ShuffleVectorSDNode::commuteMask(RMask);
24747
24748   // At this point LHS and RHS are equivalent to
24749   //   LHS = VECTOR_SHUFFLE A, B, LMask
24750   //   RHS = VECTOR_SHUFFLE A, B, RMask
24751   // Check that the masks correspond to performing a horizontal operation.
24752   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24753     for (unsigned i = 0; i != NumLaneElts; ++i) {
24754       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24755
24756       // Ignore any UNDEF components.
24757       if (LIdx < 0 || RIdx < 0 ||
24758           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24759           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24760         continue;
24761
24762       // Check that successive elements are being operated on.  If not, this is
24763       // not a horizontal operation.
24764       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24765       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24766       if (!(LIdx == Index && RIdx == Index + 1) &&
24767           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24768         return false;
24769     }
24770   }
24771
24772   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24773   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24774   return true;
24775 }
24776
24777 /// Do target-specific dag combines on floating point adds.
24778 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24779                                   const X86Subtarget *Subtarget) {
24780   EVT VT = N->getValueType(0);
24781   SDValue LHS = N->getOperand(0);
24782   SDValue RHS = N->getOperand(1);
24783
24784   // Try to synthesize horizontal adds from adds of shuffles.
24785   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24786        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24787       isHorizontalBinOp(LHS, RHS, true))
24788     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24789   return SDValue();
24790 }
24791
24792 /// Do target-specific dag combines on floating point subs.
24793 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24794                                   const X86Subtarget *Subtarget) {
24795   EVT VT = N->getValueType(0);
24796   SDValue LHS = N->getOperand(0);
24797   SDValue RHS = N->getOperand(1);
24798
24799   // Try to synthesize horizontal subs from subs of shuffles.
24800   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24801        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24802       isHorizontalBinOp(LHS, RHS, false))
24803     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24804   return SDValue();
24805 }
24806
24807 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24808 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24809   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24810
24811   // F[X]OR(0.0, x) -> x
24812   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24813     if (C->getValueAPF().isPosZero())
24814       return N->getOperand(1);
24815
24816   // F[X]OR(x, 0.0) -> x
24817   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24818     if (C->getValueAPF().isPosZero())
24819       return N->getOperand(0);
24820   return SDValue();
24821 }
24822
24823 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24824 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24825   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24826
24827   // Only perform optimizations if UnsafeMath is used.
24828   if (!DAG.getTarget().Options.UnsafeFPMath)
24829     return SDValue();
24830
24831   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24832   // into FMINC and FMAXC, which are Commutative operations.
24833   unsigned NewOp = 0;
24834   switch (N->getOpcode()) {
24835     default: llvm_unreachable("unknown opcode");
24836     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24837     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24838   }
24839
24840   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24841                      N->getOperand(0), N->getOperand(1));
24842 }
24843
24844 /// Do target-specific dag combines on X86ISD::FAND nodes.
24845 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24846   // FAND(0.0, x) -> 0.0
24847   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24848     if (C->getValueAPF().isPosZero())
24849       return N->getOperand(0);
24850
24851   // FAND(x, 0.0) -> 0.0
24852   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24853     if (C->getValueAPF().isPosZero())
24854       return N->getOperand(1);
24855
24856   return SDValue();
24857 }
24858
24859 /// Do target-specific dag combines on X86ISD::FANDN nodes
24860 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24861   // FANDN(0.0, x) -> x
24862   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24863     if (C->getValueAPF().isPosZero())
24864       return N->getOperand(1);
24865
24866   // FANDN(x, 0.0) -> 0.0
24867   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24868     if (C->getValueAPF().isPosZero())
24869       return N->getOperand(1);
24870
24871   return SDValue();
24872 }
24873
24874 static SDValue PerformBTCombine(SDNode *N,
24875                                 SelectionDAG &DAG,
24876                                 TargetLowering::DAGCombinerInfo &DCI) {
24877   // BT ignores high bits in the bit index operand.
24878   SDValue Op1 = N->getOperand(1);
24879   if (Op1.hasOneUse()) {
24880     unsigned BitWidth = Op1.getValueSizeInBits();
24881     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24882     APInt KnownZero, KnownOne;
24883     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24884                                           !DCI.isBeforeLegalizeOps());
24885     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24886     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24887         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24888       DCI.CommitTargetLoweringOpt(TLO);
24889   }
24890   return SDValue();
24891 }
24892
24893 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24894   SDValue Op = N->getOperand(0);
24895   if (Op.getOpcode() == ISD::BITCAST)
24896     Op = Op.getOperand(0);
24897   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24898   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24899       VT.getVectorElementType().getSizeInBits() ==
24900       OpVT.getVectorElementType().getSizeInBits()) {
24901     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24902   }
24903   return SDValue();
24904 }
24905
24906 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24907                                                const X86Subtarget *Subtarget) {
24908   EVT VT = N->getValueType(0);
24909   if (!VT.isVector())
24910     return SDValue();
24911
24912   SDValue N0 = N->getOperand(0);
24913   SDValue N1 = N->getOperand(1);
24914   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24915   SDLoc dl(N);
24916
24917   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24918   // both SSE and AVX2 since there is no sign-extended shift right
24919   // operation on a vector with 64-bit elements.
24920   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24921   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24922   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24923       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24924     SDValue N00 = N0.getOperand(0);
24925
24926     // EXTLOAD has a better solution on AVX2,
24927     // it may be replaced with X86ISD::VSEXT node.
24928     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24929       if (!ISD::isNormalLoad(N00.getNode()))
24930         return SDValue();
24931
24932     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24933         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24934                                   N00, N1);
24935       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24936     }
24937   }
24938   return SDValue();
24939 }
24940
24941 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24942                                   TargetLowering::DAGCombinerInfo &DCI,
24943                                   const X86Subtarget *Subtarget) {
24944   SDValue N0 = N->getOperand(0);
24945   EVT VT = N->getValueType(0);
24946   EVT SVT = VT.getScalarType();
24947   EVT InVT = N0.getValueType();
24948   EVT InSVT = InVT.getScalarType();
24949   SDLoc DL(N);
24950
24951   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24952   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24953   // This exposes the sext to the sdivrem lowering, so that it directly extends
24954   // from AH (which we otherwise need to do contortions to access).
24955   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24956       InVT == MVT::i8 && VT == MVT::i32) {
24957     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24958     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24959                             N0.getOperand(0), N0.getOperand(1));
24960     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24961     return R.getValue(1);
24962   }
24963
24964   if (!DCI.isBeforeLegalizeOps()) {
24965     if (InVT == MVT::i1) {
24966       SDValue Zero = DAG.getConstant(0, DL, VT);
24967       SDValue AllOnes =
24968         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24969       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24970     }
24971     return SDValue();
24972   }
24973
24974   if (VT.isVector() && Subtarget->hasSSE2()) {
24975     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24976       EVT InVT = N.getValueType();
24977       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24978                                    Size / InVT.getScalarSizeInBits());
24979       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24980                                     DAG.getUNDEF(InVT));
24981       Opnds[0] = N;
24982       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24983     };
24984
24985     // If target-size is less than 128-bits, extend to a type that would extend
24986     // to 128 bits, extend that and extract the original target vector.
24987     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24988         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24989         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24990       unsigned Scale = 128 / VT.getSizeInBits();
24991       EVT ExVT =
24992           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24993       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24994       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24995       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24996                          DAG.getIntPtrConstant(0, DL));
24997     }
24998
24999     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25000     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25001     if (VT.getSizeInBits() == 128 &&
25002         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25003         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25004       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25005       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25006     }
25007
25008     // On pre-AVX2 targets, split into 128-bit nodes of
25009     // ISD::SIGN_EXTEND_VECTOR_INREG.
25010     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25011         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25012         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25013       unsigned NumVecs = VT.getSizeInBits() / 128;
25014       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25015       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25016       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25017
25018       SmallVector<SDValue, 8> Opnds;
25019       for (unsigned i = 0, Offset = 0; i != NumVecs;
25020            ++i, Offset += NumSubElts) {
25021         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25022                                      DAG.getIntPtrConstant(Offset, DL));
25023         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25024         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25025         Opnds.push_back(SrcVec);
25026       }
25027       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25028     }
25029   }
25030
25031   if (!Subtarget->hasFp256())
25032     return SDValue();
25033
25034   if (VT.isVector() && VT.getSizeInBits() == 256)
25035     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25036       return R;
25037
25038   return SDValue();
25039 }
25040
25041 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25042                                  const X86Subtarget* Subtarget) {
25043   SDLoc dl(N);
25044   EVT VT = N->getValueType(0);
25045
25046   // Let legalize expand this if it isn't a legal type yet.
25047   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25048     return SDValue();
25049
25050   EVT ScalarVT = VT.getScalarType();
25051   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25052       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25053        !Subtarget->hasAVX512()))
25054     return SDValue();
25055
25056   SDValue A = N->getOperand(0);
25057   SDValue B = N->getOperand(1);
25058   SDValue C = N->getOperand(2);
25059
25060   bool NegA = (A.getOpcode() == ISD::FNEG);
25061   bool NegB = (B.getOpcode() == ISD::FNEG);
25062   bool NegC = (C.getOpcode() == ISD::FNEG);
25063
25064   // Negative multiplication when NegA xor NegB
25065   bool NegMul = (NegA != NegB);
25066   if (NegA)
25067     A = A.getOperand(0);
25068   if (NegB)
25069     B = B.getOperand(0);
25070   if (NegC)
25071     C = C.getOperand(0);
25072
25073   unsigned Opcode;
25074   if (!NegMul)
25075     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25076   else
25077     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25078
25079   return DAG.getNode(Opcode, dl, VT, A, B, C);
25080 }
25081
25082 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25083                                   TargetLowering::DAGCombinerInfo &DCI,
25084                                   const X86Subtarget *Subtarget) {
25085   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25086   //           (and (i32 x86isd::setcc_carry), 1)
25087   // This eliminates the zext. This transformation is necessary because
25088   // ISD::SETCC is always legalized to i8.
25089   SDLoc dl(N);
25090   SDValue N0 = N->getOperand(0);
25091   EVT VT = N->getValueType(0);
25092
25093   if (N0.getOpcode() == ISD::AND &&
25094       N0.hasOneUse() &&
25095       N0.getOperand(0).hasOneUse()) {
25096     SDValue N00 = N0.getOperand(0);
25097     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25098       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25099       if (!C || C->getZExtValue() != 1)
25100         return SDValue();
25101       return DAG.getNode(ISD::AND, dl, VT,
25102                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25103                                      N00.getOperand(0), N00.getOperand(1)),
25104                          DAG.getConstant(1, dl, VT));
25105     }
25106   }
25107
25108   if (N0.getOpcode() == ISD::TRUNCATE &&
25109       N0.hasOneUse() &&
25110       N0.getOperand(0).hasOneUse()) {
25111     SDValue N00 = N0.getOperand(0);
25112     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25113       return DAG.getNode(ISD::AND, dl, VT,
25114                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25115                                      N00.getOperand(0), N00.getOperand(1)),
25116                          DAG.getConstant(1, dl, VT));
25117     }
25118   }
25119
25120   if (VT.is256BitVector())
25121     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25122       return R;
25123
25124   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25125   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25126   // This exposes the zext to the udivrem lowering, so that it directly extends
25127   // from AH (which we otherwise need to do contortions to access).
25128   if (N0.getOpcode() == ISD::UDIVREM &&
25129       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25130       (VT == MVT::i32 || VT == MVT::i64)) {
25131     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25132     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25133                             N0.getOperand(0), N0.getOperand(1));
25134     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25135     return R.getValue(1);
25136   }
25137
25138   return SDValue();
25139 }
25140
25141 // Optimize x == -y --> x+y == 0
25142 //          x != -y --> x+y != 0
25143 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25144                                       const X86Subtarget* Subtarget) {
25145   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25146   SDValue LHS = N->getOperand(0);
25147   SDValue RHS = N->getOperand(1);
25148   EVT VT = N->getValueType(0);
25149   SDLoc DL(N);
25150
25151   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25152     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25153       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25154         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25155                                    LHS.getOperand(1));
25156         return DAG.getSetCC(DL, N->getValueType(0), addV,
25157                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25158       }
25159   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25160     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25161       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25162         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25163                                    RHS.getOperand(1));
25164         return DAG.getSetCC(DL, N->getValueType(0), addV,
25165                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25166       }
25167
25168   if (VT.getScalarType() == MVT::i1 &&
25169       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25170     bool IsSEXT0 =
25171         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25172         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25173     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25174
25175     if (!IsSEXT0 || !IsVZero1) {
25176       // Swap the operands and update the condition code.
25177       std::swap(LHS, RHS);
25178       CC = ISD::getSetCCSwappedOperands(CC);
25179
25180       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25181                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25182       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25183     }
25184
25185     if (IsSEXT0 && IsVZero1) {
25186       assert(VT == LHS.getOperand(0).getValueType() &&
25187              "Uexpected operand type");
25188       if (CC == ISD::SETGT)
25189         return DAG.getConstant(0, DL, VT);
25190       if (CC == ISD::SETLE)
25191         return DAG.getConstant(1, DL, VT);
25192       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25193         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25194
25195       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25196              "Unexpected condition code!");
25197       return LHS.getOperand(0);
25198     }
25199   }
25200
25201   return SDValue();
25202 }
25203
25204 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25205                                          SelectionDAG &DAG) {
25206   SDLoc dl(Load);
25207   MVT VT = Load->getSimpleValueType(0);
25208   MVT EVT = VT.getVectorElementType();
25209   SDValue Addr = Load->getOperand(1);
25210   SDValue NewAddr = DAG.getNode(
25211       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25212       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25213                       Addr.getSimpleValueType()));
25214
25215   SDValue NewLoad =
25216       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25217                   DAG.getMachineFunction().getMachineMemOperand(
25218                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25219   return NewLoad;
25220 }
25221
25222 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25223                                       const X86Subtarget *Subtarget) {
25224   SDLoc dl(N);
25225   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25226   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25227          "X86insertps is only defined for v4x32");
25228
25229   SDValue Ld = N->getOperand(1);
25230   if (MayFoldLoad(Ld)) {
25231     // Extract the countS bits from the immediate so we can get the proper
25232     // address when narrowing the vector load to a specific element.
25233     // When the second source op is a memory address, insertps doesn't use
25234     // countS and just gets an f32 from that address.
25235     unsigned DestIndex =
25236         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25237
25238     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25239
25240     // Create this as a scalar to vector to match the instruction pattern.
25241     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25242     // countS bits are ignored when loading from memory on insertps, which
25243     // means we don't need to explicitly set them to 0.
25244     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25245                        LoadScalarToVector, N->getOperand(2));
25246   }
25247   return SDValue();
25248 }
25249
25250 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25251   SDValue V0 = N->getOperand(0);
25252   SDValue V1 = N->getOperand(1);
25253   SDLoc DL(N);
25254   EVT VT = N->getValueType(0);
25255
25256   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25257   // operands and changing the mask to 1. This saves us a bunch of
25258   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25259   // x86InstrInfo knows how to commute this back after instruction selection
25260   // if it would help register allocation.
25261
25262   // TODO: If optimizing for size or a processor that doesn't suffer from
25263   // partial register update stalls, this should be transformed into a MOVSD
25264   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25265
25266   if (VT == MVT::v2f64)
25267     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25268       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25269         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25270         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25271       }
25272
25273   return SDValue();
25274 }
25275
25276 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25277 // as "sbb reg,reg", since it can be extended without zext and produces
25278 // an all-ones bit which is more useful than 0/1 in some cases.
25279 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25280                                MVT VT) {
25281   if (VT == MVT::i8)
25282     return DAG.getNode(ISD::AND, DL, VT,
25283                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25284                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25285                                    EFLAGS),
25286                        DAG.getConstant(1, DL, VT));
25287   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25288   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25289                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25290                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25291                                  EFLAGS));
25292 }
25293
25294 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25295 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25296                                    TargetLowering::DAGCombinerInfo &DCI,
25297                                    const X86Subtarget *Subtarget) {
25298   SDLoc DL(N);
25299   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25300   SDValue EFLAGS = N->getOperand(1);
25301
25302   if (CC == X86::COND_A) {
25303     // Try to convert COND_A into COND_B in an attempt to facilitate
25304     // materializing "setb reg".
25305     //
25306     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25307     // cannot take an immediate as its first operand.
25308     //
25309     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25310         EFLAGS.getValueType().isInteger() &&
25311         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25312       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25313                                    EFLAGS.getNode()->getVTList(),
25314                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25315       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25316       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25317     }
25318   }
25319
25320   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25321   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25322   // cases.
25323   if (CC == X86::COND_B)
25324     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25325
25326   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25327     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25328     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25329   }
25330
25331   return SDValue();
25332 }
25333
25334 // Optimize branch condition evaluation.
25335 //
25336 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25337                                     TargetLowering::DAGCombinerInfo &DCI,
25338                                     const X86Subtarget *Subtarget) {
25339   SDLoc DL(N);
25340   SDValue Chain = N->getOperand(0);
25341   SDValue Dest = N->getOperand(1);
25342   SDValue EFLAGS = N->getOperand(3);
25343   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25344
25345   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25346     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25347     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25348                        Flags);
25349   }
25350
25351   return SDValue();
25352 }
25353
25354 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25355                                                          SelectionDAG &DAG) {
25356   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25357   // optimize away operation when it's from a constant.
25358   //
25359   // The general transformation is:
25360   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25361   //       AND(VECTOR_CMP(x,y), constant2)
25362   //    constant2 = UNARYOP(constant)
25363
25364   // Early exit if this isn't a vector operation, the operand of the
25365   // unary operation isn't a bitwise AND, or if the sizes of the operations
25366   // aren't the same.
25367   EVT VT = N->getValueType(0);
25368   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25369       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25370       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25371     return SDValue();
25372
25373   // Now check that the other operand of the AND is a constant. We could
25374   // make the transformation for non-constant splats as well, but it's unclear
25375   // that would be a benefit as it would not eliminate any operations, just
25376   // perform one more step in scalar code before moving to the vector unit.
25377   if (BuildVectorSDNode *BV =
25378           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25379     // Bail out if the vector isn't a constant.
25380     if (!BV->isConstant())
25381       return SDValue();
25382
25383     // Everything checks out. Build up the new and improved node.
25384     SDLoc DL(N);
25385     EVT IntVT = BV->getValueType(0);
25386     // Create a new constant of the appropriate type for the transformed
25387     // DAG.
25388     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25389     // The AND node needs bitcasts to/from an integer vector type around it.
25390     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25391     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25392                                  N->getOperand(0)->getOperand(0), MaskConst);
25393     SDValue Res = DAG.getBitcast(VT, NewAnd);
25394     return Res;
25395   }
25396
25397   return SDValue();
25398 }
25399
25400 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25401                                         const X86Subtarget *Subtarget) {
25402   SDValue Op0 = N->getOperand(0);
25403   EVT VT = N->getValueType(0);
25404   EVT InVT = Op0.getValueType();
25405   EVT InSVT = InVT.getScalarType();
25406   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25407
25408   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25409   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25410   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25411     SDLoc dl(N);
25412     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25413                                  InVT.getVectorNumElements());
25414     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25415
25416     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25417       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25418
25419     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25420   }
25421
25422   return SDValue();
25423 }
25424
25425 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25426                                         const X86Subtarget *Subtarget) {
25427   // First try to optimize away the conversion entirely when it's
25428   // conditionally from a constant. Vectors only.
25429   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25430     return Res;
25431
25432   // Now move on to more general possibilities.
25433   SDValue Op0 = N->getOperand(0);
25434   EVT VT = N->getValueType(0);
25435   EVT InVT = Op0.getValueType();
25436   EVT InSVT = InVT.getScalarType();
25437
25438   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25439   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25440   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25441     SDLoc dl(N);
25442     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25443                                  InVT.getVectorNumElements());
25444     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25445     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25446   }
25447
25448   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25449   // a 32-bit target where SSE doesn't support i64->FP operations.
25450   if (Op0.getOpcode() == ISD::LOAD) {
25451     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25452     EVT LdVT = Ld->getValueType(0);
25453
25454     // This transformation is not supported if the result type is f16
25455     if (VT == MVT::f16)
25456       return SDValue();
25457
25458     if (!Ld->isVolatile() && !VT.isVector() &&
25459         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25460         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25461       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25462           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25463       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25464       return FILDChain;
25465     }
25466   }
25467   return SDValue();
25468 }
25469
25470 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25471 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25472                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25473   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25474   // the result is either zero or one (depending on the input carry bit).
25475   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25476   if (X86::isZeroNode(N->getOperand(0)) &&
25477       X86::isZeroNode(N->getOperand(1)) &&
25478       // We don't have a good way to replace an EFLAGS use, so only do this when
25479       // dead right now.
25480       SDValue(N, 1).use_empty()) {
25481     SDLoc DL(N);
25482     EVT VT = N->getValueType(0);
25483     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25484     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25485                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25486                                            DAG.getConstant(X86::COND_B, DL,
25487                                                            MVT::i8),
25488                                            N->getOperand(2)),
25489                                DAG.getConstant(1, DL, VT));
25490     return DCI.CombineTo(N, Res1, CarryOut);
25491   }
25492
25493   return SDValue();
25494 }
25495
25496 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25497 //      (add Y, (setne X, 0)) -> sbb -1, Y
25498 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25499 //      (sub (setne X, 0), Y) -> adc -1, Y
25500 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25501   SDLoc DL(N);
25502
25503   // Look through ZExts.
25504   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25505   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25506     return SDValue();
25507
25508   SDValue SetCC = Ext.getOperand(0);
25509   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25510     return SDValue();
25511
25512   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25513   if (CC != X86::COND_E && CC != X86::COND_NE)
25514     return SDValue();
25515
25516   SDValue Cmp = SetCC.getOperand(1);
25517   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25518       !X86::isZeroNode(Cmp.getOperand(1)) ||
25519       !Cmp.getOperand(0).getValueType().isInteger())
25520     return SDValue();
25521
25522   SDValue CmpOp0 = Cmp.getOperand(0);
25523   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25524                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25525
25526   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25527   if (CC == X86::COND_NE)
25528     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25529                        DL, OtherVal.getValueType(), OtherVal,
25530                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25531                        NewCmp);
25532   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25533                      DL, OtherVal.getValueType(), OtherVal,
25534                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25535 }
25536
25537 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25538 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25539                                  const X86Subtarget *Subtarget) {
25540   EVT VT = N->getValueType(0);
25541   SDValue Op0 = N->getOperand(0);
25542   SDValue Op1 = N->getOperand(1);
25543
25544   // Try to synthesize horizontal adds from adds of shuffles.
25545   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25546        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25547       isHorizontalBinOp(Op0, Op1, true))
25548     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25549
25550   return OptimizeConditionalInDecrement(N, DAG);
25551 }
25552
25553 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25554                                  const X86Subtarget *Subtarget) {
25555   SDValue Op0 = N->getOperand(0);
25556   SDValue Op1 = N->getOperand(1);
25557
25558   // X86 can't encode an immediate LHS of a sub. See if we can push the
25559   // negation into a preceding instruction.
25560   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25561     // If the RHS of the sub is a XOR with one use and a constant, invert the
25562     // immediate. Then add one to the LHS of the sub so we can turn
25563     // X-Y -> X+~Y+1, saving one register.
25564     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25565         isa<ConstantSDNode>(Op1.getOperand(1))) {
25566       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25567       EVT VT = Op0.getValueType();
25568       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25569                                    Op1.getOperand(0),
25570                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25571       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25572                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25573     }
25574   }
25575
25576   // Try to synthesize horizontal adds from adds of shuffles.
25577   EVT VT = N->getValueType(0);
25578   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25579        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25580       isHorizontalBinOp(Op0, Op1, true))
25581     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25582
25583   return OptimizeConditionalInDecrement(N, DAG);
25584 }
25585
25586 /// performVZEXTCombine - Performs build vector combines
25587 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25588                                    TargetLowering::DAGCombinerInfo &DCI,
25589                                    const X86Subtarget *Subtarget) {
25590   SDLoc DL(N);
25591   MVT VT = N->getSimpleValueType(0);
25592   SDValue Op = N->getOperand(0);
25593   MVT OpVT = Op.getSimpleValueType();
25594   MVT OpEltVT = OpVT.getVectorElementType();
25595   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25596
25597   // (vzext (bitcast (vzext (x)) -> (vzext x)
25598   SDValue V = Op;
25599   while (V.getOpcode() == ISD::BITCAST)
25600     V = V.getOperand(0);
25601
25602   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25603     MVT InnerVT = V.getSimpleValueType();
25604     MVT InnerEltVT = InnerVT.getVectorElementType();
25605
25606     // If the element sizes match exactly, we can just do one larger vzext. This
25607     // is always an exact type match as vzext operates on integer types.
25608     if (OpEltVT == InnerEltVT) {
25609       assert(OpVT == InnerVT && "Types must match for vzext!");
25610       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25611     }
25612
25613     // The only other way we can combine them is if only a single element of the
25614     // inner vzext is used in the input to the outer vzext.
25615     if (InnerEltVT.getSizeInBits() < InputBits)
25616       return SDValue();
25617
25618     // In this case, the inner vzext is completely dead because we're going to
25619     // only look at bits inside of the low element. Just do the outer vzext on
25620     // a bitcast of the input to the inner.
25621     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25622   }
25623
25624   // Check if we can bypass extracting and re-inserting an element of an input
25625   // vector. Essentially:
25626   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25627   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25628       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25629       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25630     SDValue ExtractedV = V.getOperand(0);
25631     SDValue OrigV = ExtractedV.getOperand(0);
25632     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25633       if (ExtractIdx->getZExtValue() == 0) {
25634         MVT OrigVT = OrigV.getSimpleValueType();
25635         // Extract a subvector if necessary...
25636         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25637           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25638           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25639                                     OrigVT.getVectorNumElements() / Ratio);
25640           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25641                               DAG.getIntPtrConstant(0, DL));
25642         }
25643         Op = DAG.getBitcast(OpVT, OrigV);
25644         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25645       }
25646   }
25647
25648   return SDValue();
25649 }
25650
25651 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25652                                              DAGCombinerInfo &DCI) const {
25653   SelectionDAG &DAG = DCI.DAG;
25654   switch (N->getOpcode()) {
25655   default: break;
25656   case ISD::EXTRACT_VECTOR_ELT:
25657     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25658   case ISD::VSELECT:
25659   case ISD::SELECT:
25660   case X86ISD::SHRUNKBLEND:
25661     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25662   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25663   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25664   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25665   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25666   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25667   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25668   case ISD::SHL:
25669   case ISD::SRA:
25670   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25671   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25672   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25673   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25674   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25675   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25676   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25677   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25678   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25679   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25680   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25681   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25682   case X86ISD::FXOR:
25683   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25684   case X86ISD::FMIN:
25685   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25686   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25687   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25688   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25689   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25690   case ISD::ANY_EXTEND:
25691   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25692   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25693   case ISD::SIGN_EXTEND_INREG:
25694     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25695   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25696   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25697   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25698   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25699   case X86ISD::SHUFP:       // Handle all target specific shuffles
25700   case X86ISD::PALIGNR:
25701   case X86ISD::UNPCKH:
25702   case X86ISD::UNPCKL:
25703   case X86ISD::MOVHLPS:
25704   case X86ISD::MOVLHPS:
25705   case X86ISD::PSHUFB:
25706   case X86ISD::PSHUFD:
25707   case X86ISD::PSHUFHW:
25708   case X86ISD::PSHUFLW:
25709   case X86ISD::MOVSS:
25710   case X86ISD::MOVSD:
25711   case X86ISD::VPERMILPI:
25712   case X86ISD::VPERM2X128:
25713   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25714   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25715   case X86ISD::INSERTPS: {
25716     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25717       return PerformINSERTPSCombine(N, DAG, Subtarget);
25718     break;
25719   }
25720   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25721   }
25722
25723   return SDValue();
25724 }
25725
25726 /// isTypeDesirableForOp - Return true if the target has native support for
25727 /// the specified value type and it is 'desirable' to use the type for the
25728 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25729 /// instruction encodings are longer and some i16 instructions are slow.
25730 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25731   if (!isTypeLegal(VT))
25732     return false;
25733   if (VT != MVT::i16)
25734     return true;
25735
25736   switch (Opc) {
25737   default:
25738     return true;
25739   case ISD::LOAD:
25740   case ISD::SIGN_EXTEND:
25741   case ISD::ZERO_EXTEND:
25742   case ISD::ANY_EXTEND:
25743   case ISD::SHL:
25744   case ISD::SRL:
25745   case ISD::SUB:
25746   case ISD::ADD:
25747   case ISD::MUL:
25748   case ISD::AND:
25749   case ISD::OR:
25750   case ISD::XOR:
25751     return false;
25752   }
25753 }
25754
25755 /// IsDesirableToPromoteOp - This method query the target whether it is
25756 /// beneficial for dag combiner to promote the specified node. If true, it
25757 /// should return the desired promotion type by reference.
25758 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25759   EVT VT = Op.getValueType();
25760   if (VT != MVT::i16)
25761     return false;
25762
25763   bool Promote = false;
25764   bool Commute = false;
25765   switch (Op.getOpcode()) {
25766   default: break;
25767   case ISD::LOAD: {
25768     LoadSDNode *LD = cast<LoadSDNode>(Op);
25769     // If the non-extending load has a single use and it's not live out, then it
25770     // might be folded.
25771     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25772                                                      Op.hasOneUse()*/) {
25773       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25774              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25775         // The only case where we'd want to promote LOAD (rather then it being
25776         // promoted as an operand is when it's only use is liveout.
25777         if (UI->getOpcode() != ISD::CopyToReg)
25778           return false;
25779       }
25780     }
25781     Promote = true;
25782     break;
25783   }
25784   case ISD::SIGN_EXTEND:
25785   case ISD::ZERO_EXTEND:
25786   case ISD::ANY_EXTEND:
25787     Promote = true;
25788     break;
25789   case ISD::SHL:
25790   case ISD::SRL: {
25791     SDValue N0 = Op.getOperand(0);
25792     // Look out for (store (shl (load), x)).
25793     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25794       return false;
25795     Promote = true;
25796     break;
25797   }
25798   case ISD::ADD:
25799   case ISD::MUL:
25800   case ISD::AND:
25801   case ISD::OR:
25802   case ISD::XOR:
25803     Commute = true;
25804     // fallthrough
25805   case ISD::SUB: {
25806     SDValue N0 = Op.getOperand(0);
25807     SDValue N1 = Op.getOperand(1);
25808     if (!Commute && MayFoldLoad(N1))
25809       return false;
25810     // Avoid disabling potential load folding opportunities.
25811     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25812       return false;
25813     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25814       return false;
25815     Promote = true;
25816   }
25817   }
25818
25819   PVT = MVT::i32;
25820   return Promote;
25821 }
25822
25823 //===----------------------------------------------------------------------===//
25824 //                           X86 Inline Assembly Support
25825 //===----------------------------------------------------------------------===//
25826
25827 // Helper to match a string separated by whitespace.
25828 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25829   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25830
25831   for (StringRef Piece : Pieces) {
25832     if (!S.startswith(Piece)) // Check if the piece matches.
25833       return false;
25834
25835     S = S.substr(Piece.size());
25836     StringRef::size_type Pos = S.find_first_not_of(" \t");
25837     if (Pos == 0) // We matched a prefix.
25838       return false;
25839
25840     S = S.substr(Pos);
25841   }
25842
25843   return S.empty();
25844 }
25845
25846 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25847
25848   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25849     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25850         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25851         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25852
25853       if (AsmPieces.size() == 3)
25854         return true;
25855       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25856         return true;
25857     }
25858   }
25859   return false;
25860 }
25861
25862 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25863   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25864
25865   std::string AsmStr = IA->getAsmString();
25866
25867   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25868   if (!Ty || Ty->getBitWidth() % 16 != 0)
25869     return false;
25870
25871   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25872   SmallVector<StringRef, 4> AsmPieces;
25873   SplitString(AsmStr, AsmPieces, ";\n");
25874
25875   switch (AsmPieces.size()) {
25876   default: return false;
25877   case 1:
25878     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25879     // we will turn this bswap into something that will be lowered to logical
25880     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25881     // lower so don't worry about this.
25882     // bswap $0
25883     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25884         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25885         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25886         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25887         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25888         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25889       // No need to check constraints, nothing other than the equivalent of
25890       // "=r,0" would be valid here.
25891       return IntrinsicLowering::LowerToByteSwap(CI);
25892     }
25893
25894     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25895     if (CI->getType()->isIntegerTy(16) &&
25896         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25897         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25898          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25899       AsmPieces.clear();
25900       StringRef ConstraintsStr = IA->getConstraintString();
25901       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25902       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25903       if (clobbersFlagRegisters(AsmPieces))
25904         return IntrinsicLowering::LowerToByteSwap(CI);
25905     }
25906     break;
25907   case 3:
25908     if (CI->getType()->isIntegerTy(32) &&
25909         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25910         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25911         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25912         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25913       AsmPieces.clear();
25914       StringRef ConstraintsStr = IA->getConstraintString();
25915       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25916       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25917       if (clobbersFlagRegisters(AsmPieces))
25918         return IntrinsicLowering::LowerToByteSwap(CI);
25919     }
25920
25921     if (CI->getType()->isIntegerTy(64)) {
25922       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25923       if (Constraints.size() >= 2 &&
25924           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25925           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25926         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25927         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25928             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25929             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25930           return IntrinsicLowering::LowerToByteSwap(CI);
25931       }
25932     }
25933     break;
25934   }
25935   return false;
25936 }
25937
25938 /// getConstraintType - Given a constraint letter, return the type of
25939 /// constraint it is for this target.
25940 X86TargetLowering::ConstraintType
25941 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25942   if (Constraint.size() == 1) {
25943     switch (Constraint[0]) {
25944     case 'R':
25945     case 'q':
25946     case 'Q':
25947     case 'f':
25948     case 't':
25949     case 'u':
25950     case 'y':
25951     case 'x':
25952     case 'Y':
25953     case 'l':
25954       return C_RegisterClass;
25955     case 'a':
25956     case 'b':
25957     case 'c':
25958     case 'd':
25959     case 'S':
25960     case 'D':
25961     case 'A':
25962       return C_Register;
25963     case 'I':
25964     case 'J':
25965     case 'K':
25966     case 'L':
25967     case 'M':
25968     case 'N':
25969     case 'G':
25970     case 'C':
25971     case 'e':
25972     case 'Z':
25973       return C_Other;
25974     default:
25975       break;
25976     }
25977   }
25978   return TargetLowering::getConstraintType(Constraint);
25979 }
25980
25981 /// Examine constraint type and operand type and determine a weight value.
25982 /// This object must already have been set up with the operand type
25983 /// and the current alternative constraint selected.
25984 TargetLowering::ConstraintWeight
25985   X86TargetLowering::getSingleConstraintMatchWeight(
25986     AsmOperandInfo &info, const char *constraint) const {
25987   ConstraintWeight weight = CW_Invalid;
25988   Value *CallOperandVal = info.CallOperandVal;
25989     // If we don't have a value, we can't do a match,
25990     // but allow it at the lowest weight.
25991   if (!CallOperandVal)
25992     return CW_Default;
25993   Type *type = CallOperandVal->getType();
25994   // Look at the constraint type.
25995   switch (*constraint) {
25996   default:
25997     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25998   case 'R':
25999   case 'q':
26000   case 'Q':
26001   case 'a':
26002   case 'b':
26003   case 'c':
26004   case 'd':
26005   case 'S':
26006   case 'D':
26007   case 'A':
26008     if (CallOperandVal->getType()->isIntegerTy())
26009       weight = CW_SpecificReg;
26010     break;
26011   case 'f':
26012   case 't':
26013   case 'u':
26014     if (type->isFloatingPointTy())
26015       weight = CW_SpecificReg;
26016     break;
26017   case 'y':
26018     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26019       weight = CW_SpecificReg;
26020     break;
26021   case 'x':
26022   case 'Y':
26023     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26024         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26025       weight = CW_Register;
26026     break;
26027   case 'I':
26028     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26029       if (C->getZExtValue() <= 31)
26030         weight = CW_Constant;
26031     }
26032     break;
26033   case 'J':
26034     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26035       if (C->getZExtValue() <= 63)
26036         weight = CW_Constant;
26037     }
26038     break;
26039   case 'K':
26040     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26041       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26042         weight = CW_Constant;
26043     }
26044     break;
26045   case 'L':
26046     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26047       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26048         weight = CW_Constant;
26049     }
26050     break;
26051   case 'M':
26052     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26053       if (C->getZExtValue() <= 3)
26054         weight = CW_Constant;
26055     }
26056     break;
26057   case 'N':
26058     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26059       if (C->getZExtValue() <= 0xff)
26060         weight = CW_Constant;
26061     }
26062     break;
26063   case 'G':
26064   case 'C':
26065     if (isa<ConstantFP>(CallOperandVal)) {
26066       weight = CW_Constant;
26067     }
26068     break;
26069   case 'e':
26070     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26071       if ((C->getSExtValue() >= -0x80000000LL) &&
26072           (C->getSExtValue() <= 0x7fffffffLL))
26073         weight = CW_Constant;
26074     }
26075     break;
26076   case 'Z':
26077     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26078       if (C->getZExtValue() <= 0xffffffff)
26079         weight = CW_Constant;
26080     }
26081     break;
26082   }
26083   return weight;
26084 }
26085
26086 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26087 /// with another that has more specific requirements based on the type of the
26088 /// corresponding operand.
26089 const char *X86TargetLowering::
26090 LowerXConstraint(EVT ConstraintVT) const {
26091   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26092   // 'f' like normal targets.
26093   if (ConstraintVT.isFloatingPoint()) {
26094     if (Subtarget->hasSSE2())
26095       return "Y";
26096     if (Subtarget->hasSSE1())
26097       return "x";
26098   }
26099
26100   return TargetLowering::LowerXConstraint(ConstraintVT);
26101 }
26102
26103 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26104 /// vector.  If it is invalid, don't add anything to Ops.
26105 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26106                                                      std::string &Constraint,
26107                                                      std::vector<SDValue>&Ops,
26108                                                      SelectionDAG &DAG) const {
26109   SDValue Result;
26110
26111   // Only support length 1 constraints for now.
26112   if (Constraint.length() > 1) return;
26113
26114   char ConstraintLetter = Constraint[0];
26115   switch (ConstraintLetter) {
26116   default: break;
26117   case 'I':
26118     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26119       if (C->getZExtValue() <= 31) {
26120         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26121                                        Op.getValueType());
26122         break;
26123       }
26124     }
26125     return;
26126   case 'J':
26127     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26128       if (C->getZExtValue() <= 63) {
26129         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26130                                        Op.getValueType());
26131         break;
26132       }
26133     }
26134     return;
26135   case 'K':
26136     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26137       if (isInt<8>(C->getSExtValue())) {
26138         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26139                                        Op.getValueType());
26140         break;
26141       }
26142     }
26143     return;
26144   case 'L':
26145     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26146       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26147           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26148         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26149                                        Op.getValueType());
26150         break;
26151       }
26152     }
26153     return;
26154   case 'M':
26155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26156       if (C->getZExtValue() <= 3) {
26157         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26158                                        Op.getValueType());
26159         break;
26160       }
26161     }
26162     return;
26163   case 'N':
26164     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26165       if (C->getZExtValue() <= 255) {
26166         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26167                                        Op.getValueType());
26168         break;
26169       }
26170     }
26171     return;
26172   case 'O':
26173     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26174       if (C->getZExtValue() <= 127) {
26175         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26176                                        Op.getValueType());
26177         break;
26178       }
26179     }
26180     return;
26181   case 'e': {
26182     // 32-bit signed value
26183     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26184       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26185                                            C->getSExtValue())) {
26186         // Widen to 64 bits here to get it sign extended.
26187         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26188         break;
26189       }
26190     // FIXME gcc accepts some relocatable values here too, but only in certain
26191     // memory models; it's complicated.
26192     }
26193     return;
26194   }
26195   case 'Z': {
26196     // 32-bit unsigned value
26197     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26198       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26199                                            C->getZExtValue())) {
26200         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26201                                        Op.getValueType());
26202         break;
26203       }
26204     }
26205     // FIXME gcc accepts some relocatable values here too, but only in certain
26206     // memory models; it's complicated.
26207     return;
26208   }
26209   case 'i': {
26210     // Literal immediates are always ok.
26211     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26212       // Widen to 64 bits here to get it sign extended.
26213       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26214       break;
26215     }
26216
26217     // In any sort of PIC mode addresses need to be computed at runtime by
26218     // adding in a register or some sort of table lookup.  These can't
26219     // be used as immediates.
26220     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26221       return;
26222
26223     // If we are in non-pic codegen mode, we allow the address of a global (with
26224     // an optional displacement) to be used with 'i'.
26225     GlobalAddressSDNode *GA = nullptr;
26226     int64_t Offset = 0;
26227
26228     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26229     while (1) {
26230       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26231         Offset += GA->getOffset();
26232         break;
26233       } else if (Op.getOpcode() == ISD::ADD) {
26234         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26235           Offset += C->getZExtValue();
26236           Op = Op.getOperand(0);
26237           continue;
26238         }
26239       } else if (Op.getOpcode() == ISD::SUB) {
26240         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26241           Offset += -C->getZExtValue();
26242           Op = Op.getOperand(0);
26243           continue;
26244         }
26245       }
26246
26247       // Otherwise, this isn't something we can handle, reject it.
26248       return;
26249     }
26250
26251     const GlobalValue *GV = GA->getGlobal();
26252     // If we require an extra load to get this address, as in PIC mode, we
26253     // can't accept it.
26254     if (isGlobalStubReference(
26255             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26256       return;
26257
26258     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26259                                         GA->getValueType(0), Offset);
26260     break;
26261   }
26262   }
26263
26264   if (Result.getNode()) {
26265     Ops.push_back(Result);
26266     return;
26267   }
26268   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26269 }
26270
26271 std::pair<unsigned, const TargetRegisterClass *>
26272 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26273                                                 StringRef Constraint,
26274                                                 MVT VT) const {
26275   // First, see if this is a constraint that directly corresponds to an LLVM
26276   // register class.
26277   if (Constraint.size() == 1) {
26278     // GCC Constraint Letters
26279     switch (Constraint[0]) {
26280     default: break;
26281       // TODO: Slight differences here in allocation order and leaving
26282       // RIP in the class. Do they matter any more here than they do
26283       // in the normal allocation?
26284     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26285       if (Subtarget->is64Bit()) {
26286         if (VT == MVT::i32 || VT == MVT::f32)
26287           return std::make_pair(0U, &X86::GR32RegClass);
26288         if (VT == MVT::i16)
26289           return std::make_pair(0U, &X86::GR16RegClass);
26290         if (VT == MVT::i8 || VT == MVT::i1)
26291           return std::make_pair(0U, &X86::GR8RegClass);
26292         if (VT == MVT::i64 || VT == MVT::f64)
26293           return std::make_pair(0U, &X86::GR64RegClass);
26294         break;
26295       }
26296       // 32-bit fallthrough
26297     case 'Q':   // Q_REGS
26298       if (VT == MVT::i32 || VT == MVT::f32)
26299         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26300       if (VT == MVT::i16)
26301         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26302       if (VT == MVT::i8 || VT == MVT::i1)
26303         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26304       if (VT == MVT::i64)
26305         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26306       break;
26307     case 'r':   // GENERAL_REGS
26308     case 'l':   // INDEX_REGS
26309       if (VT == MVT::i8 || VT == MVT::i1)
26310         return std::make_pair(0U, &X86::GR8RegClass);
26311       if (VT == MVT::i16)
26312         return std::make_pair(0U, &X86::GR16RegClass);
26313       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26314         return std::make_pair(0U, &X86::GR32RegClass);
26315       return std::make_pair(0U, &X86::GR64RegClass);
26316     case 'R':   // LEGACY_REGS
26317       if (VT == MVT::i8 || VT == MVT::i1)
26318         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26319       if (VT == MVT::i16)
26320         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26321       if (VT == MVT::i32 || !Subtarget->is64Bit())
26322         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26323       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26324     case 'f':  // FP Stack registers.
26325       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26326       // value to the correct fpstack register class.
26327       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26328         return std::make_pair(0U, &X86::RFP32RegClass);
26329       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26330         return std::make_pair(0U, &X86::RFP64RegClass);
26331       return std::make_pair(0U, &X86::RFP80RegClass);
26332     case 'y':   // MMX_REGS if MMX allowed.
26333       if (!Subtarget->hasMMX()) break;
26334       return std::make_pair(0U, &X86::VR64RegClass);
26335     case 'Y':   // SSE_REGS if SSE2 allowed
26336       if (!Subtarget->hasSSE2()) break;
26337       // FALL THROUGH.
26338     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26339       if (!Subtarget->hasSSE1()) break;
26340
26341       switch (VT.SimpleTy) {
26342       default: break;
26343       // Scalar SSE types.
26344       case MVT::f32:
26345       case MVT::i32:
26346         return std::make_pair(0U, &X86::FR32RegClass);
26347       case MVT::f64:
26348       case MVT::i64:
26349         return std::make_pair(0U, &X86::FR64RegClass);
26350       // Vector types.
26351       case MVT::v16i8:
26352       case MVT::v8i16:
26353       case MVT::v4i32:
26354       case MVT::v2i64:
26355       case MVT::v4f32:
26356       case MVT::v2f64:
26357         return std::make_pair(0U, &X86::VR128RegClass);
26358       // AVX types.
26359       case MVT::v32i8:
26360       case MVT::v16i16:
26361       case MVT::v8i32:
26362       case MVT::v4i64:
26363       case MVT::v8f32:
26364       case MVT::v4f64:
26365         return std::make_pair(0U, &X86::VR256RegClass);
26366       case MVT::v8f64:
26367       case MVT::v16f32:
26368       case MVT::v16i32:
26369       case MVT::v8i64:
26370         return std::make_pair(0U, &X86::VR512RegClass);
26371       }
26372       break;
26373     }
26374   }
26375
26376   // Use the default implementation in TargetLowering to convert the register
26377   // constraint into a member of a register class.
26378   std::pair<unsigned, const TargetRegisterClass*> Res;
26379   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26380
26381   // Not found as a standard register?
26382   if (!Res.second) {
26383     // Map st(0) -> st(7) -> ST0
26384     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26385         tolower(Constraint[1]) == 's' &&
26386         tolower(Constraint[2]) == 't' &&
26387         Constraint[3] == '(' &&
26388         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26389         Constraint[5] == ')' &&
26390         Constraint[6] == '}') {
26391
26392       Res.first = X86::FP0+Constraint[4]-'0';
26393       Res.second = &X86::RFP80RegClass;
26394       return Res;
26395     }
26396
26397     // GCC allows "st(0)" to be called just plain "st".
26398     if (StringRef("{st}").equals_lower(Constraint)) {
26399       Res.first = X86::FP0;
26400       Res.second = &X86::RFP80RegClass;
26401       return Res;
26402     }
26403
26404     // flags -> EFLAGS
26405     if (StringRef("{flags}").equals_lower(Constraint)) {
26406       Res.first = X86::EFLAGS;
26407       Res.second = &X86::CCRRegClass;
26408       return Res;
26409     }
26410
26411     // 'A' means EAX + EDX.
26412     if (Constraint == "A") {
26413       Res.first = X86::EAX;
26414       Res.second = &X86::GR32_ADRegClass;
26415       return Res;
26416     }
26417     return Res;
26418   }
26419
26420   // Otherwise, check to see if this is a register class of the wrong value
26421   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26422   // turn into {ax},{dx}.
26423   // MVT::Other is used to specify clobber names.
26424   if (Res.second->hasType(VT) || VT == MVT::Other)
26425     return Res;   // Correct type already, nothing to do.
26426
26427   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26428   // return "eax". This should even work for things like getting 64bit integer
26429   // registers when given an f64 type.
26430   const TargetRegisterClass *Class = Res.second;
26431   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26432       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26433     unsigned Size = VT.getSizeInBits();
26434     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26435                                   : Size == 16 ? MVT::i16
26436                                   : Size == 32 ? MVT::i32
26437                                   : Size == 64 ? MVT::i64
26438                                   : MVT::Other;
26439     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26440     if (DestReg > 0) {
26441       Res.first = DestReg;
26442       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26443                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26444                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26445                  : &X86::GR64RegClass;
26446       assert(Res.second->contains(Res.first) && "Register in register class");
26447     } else {
26448       // No register found/type mismatch.
26449       Res.first = 0;
26450       Res.second = nullptr;
26451     }
26452   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26453              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26454              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26455              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26456              Class == &X86::VR512RegClass) {
26457     // Handle references to XMM physical registers that got mapped into the
26458     // wrong class.  This can happen with constraints like {xmm0} where the
26459     // target independent register mapper will just pick the first match it can
26460     // find, ignoring the required type.
26461
26462     if (VT == MVT::f32 || VT == MVT::i32)
26463       Res.second = &X86::FR32RegClass;
26464     else if (VT == MVT::f64 || VT == MVT::i64)
26465       Res.second = &X86::FR64RegClass;
26466     else if (X86::VR128RegClass.hasType(VT))
26467       Res.second = &X86::VR128RegClass;
26468     else if (X86::VR256RegClass.hasType(VT))
26469       Res.second = &X86::VR256RegClass;
26470     else if (X86::VR512RegClass.hasType(VT))
26471       Res.second = &X86::VR512RegClass;
26472     else {
26473       // Type mismatch and not a clobber: Return an error;
26474       Res.first = 0;
26475       Res.second = nullptr;
26476     }
26477   }
26478
26479   return Res;
26480 }
26481
26482 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26483                                             const AddrMode &AM, Type *Ty,
26484                                             unsigned AS) const {
26485   // Scaling factors are not free at all.
26486   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26487   // will take 2 allocations in the out of order engine instead of 1
26488   // for plain addressing mode, i.e. inst (reg1).
26489   // E.g.,
26490   // vaddps (%rsi,%drx), %ymm0, %ymm1
26491   // Requires two allocations (one for the load, one for the computation)
26492   // whereas:
26493   // vaddps (%rsi), %ymm0, %ymm1
26494   // Requires just 1 allocation, i.e., freeing allocations for other operations
26495   // and having less micro operations to execute.
26496   //
26497   // For some X86 architectures, this is even worse because for instance for
26498   // stores, the complex addressing mode forces the instruction to use the
26499   // "load" ports instead of the dedicated "store" port.
26500   // E.g., on Haswell:
26501   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26502   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26503   if (isLegalAddressingMode(DL, AM, Ty, AS))
26504     // Scale represents reg2 * scale, thus account for 1
26505     // as soon as we use a second register.
26506     return AM.Scale != 0;
26507   return -1;
26508 }
26509
26510 bool X86TargetLowering::isTargetFTOL() const {
26511   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26512 }
26513
26514 bool X86TargetLowering::isIntDivCheap(EVT VT, bool OptSize) const {
26515   // Integer division on x86 is expensive. However, when aggressively optimizing
26516   // for code size, we prefer to use a div instruction, as it is usually smaller
26517   // than the alternative sequence.
26518   // The exception to this is vector division. Since x86 doesn't have vector
26519   // integer division, leaving the division as-is is a loss even in terms of
26520   // size, because it will have to be scalarized, while the alternative code
26521   // sequence can be performed in vector form.
26522   return OptSize && !VT.isVector();
26523 }