[SEH] Emit 32-bit SEH tables for the new EH IR
[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
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
168     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
169   } else if (!Subtarget->useSoftFloat()) {
170     // We have an algorithm for SSE2->double, and we turn this into a
171     // 64-bit FILD followed by conditional FADD for other targets.
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173     // We have an algorithm for SSE2, and we turn this into a 64-bit
174     // FILD for other targets.
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
176   }
177
178   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
179   // this operation.
180   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
181   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
182
183   if (!Subtarget->useSoftFloat()) {
184     // SSE has no i16 to fp conversion, only i32
185     if (X86ScalarSSEf32) {
186       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
187       // f32 and f64 cases are Legal, f80 case is not
188       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
189     } else {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
192     }
193   } else {
194     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
195     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
196   }
197
198   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
199   // are Legal, f80 is custom lowered.
200   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
201   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (X86ScalarSSEf32) {
209     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
210     // f32 and f64 cases are Legal, f80 case is not
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
212   } else {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
214     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
215   }
216
217   // Handle FP_TO_UINT by promoting the destination to a larger signed
218   // conversion.
219   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
220   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
221   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
222
223   if (Subtarget->is64Bit()) {
224     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
227       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
228     } else {
229       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
231     }
232   } else if (!Subtarget->useSoftFloat()) {
233     // Since AVX is a superset of SSE3, only check for SSE here.
234     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235       // Expand FP_TO_UINT into a select.
236       // FIXME: We would like to use a Custom expander here eventually to do
237       // the optimal thing for SSE vs. the default expansion in the legalizer.
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
239     else
240       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
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     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
246   }
247
248   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249   if (!X86ScalarSSEf64) {
250     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
251     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
252     if (Subtarget->is64Bit()) {
253       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
254       // Without SSE, i64->f64 goes through memory.
255       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
256     }
257   }
258
259   // Scalar integer divide and remainder are lowered to use operations that
260   // produce two results, to match the available instructions. This exposes
261   // the two-result form to trivial CSE, which is able to combine x/y and x%y
262   // into a single instruction.
263   //
264   // Scalar integer multiply-high is also lowered to use two-result
265   // operations, to match the available instructions. However, plain multiply
266   // (low) operations are left as Legal, as there are single-result
267   // instructions for this in x86. Using the two-result multiply instructions
268   // when both high and low results are needed must be arranged by dagcombine.
269   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
270     MVT VT = IntVTs[i];
271     setOperationAction(ISD::MULHS, VT, Expand);
272     setOperationAction(ISD::MULHU, VT, Expand);
273     setOperationAction(ISD::SDIV, VT, Expand);
274     setOperationAction(ISD::UDIV, VT, Expand);
275     setOperationAction(ISD::SREM, VT, Expand);
276     setOperationAction(ISD::UREM, VT, Expand);
277
278     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279     setOperationAction(ISD::ADDC, VT, Custom);
280     setOperationAction(ISD::ADDE, VT, Custom);
281     setOperationAction(ISD::SUBC, VT, Custom);
282     setOperationAction(ISD::SUBE, VT, Custom);
283   }
284
285   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
286   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
287   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
288   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
289   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
290   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
291   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
294   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
295   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
296   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
301   if (Subtarget->is64Bit())
302     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
304   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
305   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
306   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
307
308   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
309     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
310     // is. We should promote the value to 64-bits to solve this.
311     // This is what the CRT headers do - `fmodf` is an inline header
312     // function casting to f64 and calling `fmod`.
313     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
314   } else {
315     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
316   }
317
318   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
319   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
320   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
321
322   // Promote the i8 variants and force them on up to i32 which has a shorter
323   // encoding.
324   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
326   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
327   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
328   if (Subtarget->hasBMI()) {
329     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
330     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
331     if (Subtarget->is64Bit())
332       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
333   } else {
334     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
335     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
336     if (Subtarget->is64Bit())
337       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
338   }
339
340   if (Subtarget->hasLZCNT()) {
341     // When promoting the i8 variants, force them to i32 for a shorter
342     // encoding.
343     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
346     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
348     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
349     if (Subtarget->is64Bit())
350       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
351   } else {
352     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
353     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
354     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
358     if (Subtarget->is64Bit()) {
359       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
360       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
361     }
362   }
363
364   // Special handling for half-precision floating point conversions.
365   // If we don't have F16C support, then lower half float conversions
366   // into library calls.
367   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
368     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
369     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
370   }
371
372   // There's never any support for operations beyond MVT::f32.
373   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
374   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
375   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
376   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
377
378   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
382   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
384
385   if (Subtarget->hasPOPCNT()) {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
387   } else {
388     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
389     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
390     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
391     if (Subtarget->is64Bit())
392       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
393   }
394
395   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
396
397   if (!Subtarget->hasMOVBE())
398     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
399
400   // These should be promoted to a larger select which is supported.
401   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
402   // X86 wants to expand cmov itself.
403   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
404   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
410   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
417     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
418   }
419   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
420   setOperationAction(ISD::CATCHRET        , MVT::Other, Custom);
421   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
422   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
423   // support continuation, user-level threading, and etc.. As a result, no
424   // other SjLj exception interfaces are implemented and please don't build
425   // your own exception handling based on them.
426   // LLVM/Clang supports zero-cost DWARF exception handling.
427   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
428   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
429
430   // Darwin ABI issue.
431   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
432   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
433   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
434   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
435   if (Subtarget->is64Bit())
436     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
437   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
438   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
439   if (Subtarget->is64Bit()) {
440     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
441     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
442     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
443     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
444     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
445   }
446   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
447   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
448   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
449   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
450   if (Subtarget->is64Bit()) {
451     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
452     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
453     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
454   }
455
456   if (Subtarget->hasSSE1())
457     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
458
459   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
460
461   // Expand certain atomics
462   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
463     MVT VT = IntVTs[i];
464     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
465     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
466     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
467   }
468
469   if (Subtarget->hasCmpxchg16b()) {
470     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
471   }
472
473   // FIXME - use subtarget debug flags
474   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
475       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
476     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
477   }
478
479   if (Subtarget->isTarget64BitLP64()) {
480     setExceptionPointerRegister(X86::RAX);
481     setExceptionSelectorRegister(X86::RDX);
482   } else {
483     setExceptionPointerRegister(X86::EAX);
484     setExceptionSelectorRegister(X86::EDX);
485   }
486   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
487   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
488
489   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
490   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
491
492   setOperationAction(ISD::TRAP, MVT::Other, Legal);
493   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
494
495   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
496   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
497   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
498   if (Subtarget->is64Bit()) {
499     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
500     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
501   } else {
502     // TargetInfo::CharPtrBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
505   }
506
507   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
508   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
509
510   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
511
512   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
513   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
514   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
515
516   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!Subtarget->useSoftFloat()) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!Subtarget->useSoftFloat()) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749
750       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
751       // split/scalarized right now.
752       if (VT.getVectorElementType() == MVT::f16)
753         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
754     }
755   }
756
757   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
758   // with -msoft-float, disable use of MMX as well.
759   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
760     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
761     // No operations on x86mmx supported, everything uses intrinsics.
762   }
763
764   // MMX-sized vectors (other than x86mmx) are expected to be expanded
765   // into smaller operations.
766   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
767     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
768     setOperationAction(ISD::AND,                MMXTy,      Expand);
769     setOperationAction(ISD::OR,                 MMXTy,      Expand);
770     setOperationAction(ISD::XOR,                MMXTy,      Expand);
771     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
772     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
773     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
774   }
775   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
776
777   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
778     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
779
780     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
785     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
786     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
787     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
788     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
789     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
790     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
791     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
793     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
794   }
795
796   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
797     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
798
799     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
800     // registers cannot be used even for integer operations.
801     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
802     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
803     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
804     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
805
806     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
807     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
808     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
809     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
810     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
811     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
812     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
813     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
815     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
816     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
818     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
819     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
820     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
821     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
822     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
827     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
828     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
829
830     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
832     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
833     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
834
835     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
838     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
839
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
841     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
845
846     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
849     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
850
851     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
852     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
853       MVT VT = (MVT::SimpleValueType)i;
854       // Do not attempt to custom lower non-power-of-2 vectors
855       if (!isPowerOf2_32(VT.getVectorNumElements()))
856         continue;
857       // Do not attempt to custom lower non-128-bit vectors
858       if (!VT.is128BitVector())
859         continue;
860       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
862       setOperationAction(ISD::VSELECT,            VT, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
864     }
865
866     // We support custom legalizing of sext and anyext loads for specific
867     // memory vector types which we can load as a scalar (or sequence of
868     // scalars) and extend in-register to a legal 128-bit vector type. For sext
869     // loads these must work with a single scalar load.
870     for (MVT VT : MVT::integer_vector_valuetypes()) {
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
872       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
880     }
881
882     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
884     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
886     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
887     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
888     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
889     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
890
891     if (Subtarget->is64Bit()) {
892       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
893       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
894     }
895
896     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
897     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
898       MVT VT = (MVT::SimpleValueType)i;
899
900       // Do not attempt to promote non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903
904       setOperationAction(ISD::AND,    VT, Promote);
905       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
906       setOperationAction(ISD::OR,     VT, Promote);
907       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
908       setOperationAction(ISD::XOR,    VT, Promote);
909       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
910       setOperationAction(ISD::LOAD,   VT, Promote);
911       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
912       setOperationAction(ISD::SELECT, VT, Promote);
913       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914     }
915
916     // Custom lower v2i64 and v2f64 selects.
917     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
918     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
919     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
920     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
921
922     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
924
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
958     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
959     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
960     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
961     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
962
963     // FIXME: Do we need to handle scalar-to-vector here?
964     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
965
966     // We directly match byte blends in the backend as they match the VSELECT
967     // condition form.
968     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
969
970     // SSE41 brings specific instructions for doing vector sign extend even in
971     // cases where we don't have SRA.
972     for (MVT VT : MVT::integer_vector_valuetypes()) {
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
974       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976     }
977
978     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
983     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
984     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
985
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
990     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
991     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
992
993     // i8 and i16 vectors are custom because the source register and source
994     // source memory operand types are not the same width.  f32 vectors are
995     // custom since the immediate controlling the insert encodes additional
996     // information.
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1001
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1005     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1006
1007     // FIXME: these should be Legal, but that's only for the case where
1008     // the index is constant.  For now custom expand to deal with that.
1009     if (Subtarget->is64Bit()) {
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1012     }
1013   }
1014
1015   if (Subtarget->hasSSE2()) {
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1019
1020     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1022
1023     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1024     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1025
1026     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1027     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1028
1029     // In the customized shift lowering, the legal cases in AVX2 will be
1030     // recognized.
1031     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1033
1034     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1035     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1036
1037     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1038     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1039   }
1040
1041   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1042     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1044     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1046     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1047     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1048
1049     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1051     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1052
1053     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1056     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1061     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1062     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1063     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1064     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1065
1066     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1069     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1070     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1076     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1077     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1078
1079     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1080     // even though v8i16 is a legal type.
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1082     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1083     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1084
1085     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1086     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1087     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1088
1089     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1090     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1091
1092     for (MVT VT : MVT::fp_vector_valuetypes())
1093       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1094
1095     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1099     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1100
1101     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1102     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1103
1104     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1106     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1107     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1108
1109     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1110     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1111     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1112
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1114     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1115     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1117     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1118     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1120     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1121     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1123     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1124     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1125
1126     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1128     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1129     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1130
1131     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1132       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1136       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1137       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1138     }
1139
1140     if (Subtarget->hasInt256()) {
1141       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1143       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1144       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1145
1146       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1148       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1149       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1150
1151       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1152       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1153       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1154       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1155
1156       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1157       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1158       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1159       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1160
1161       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1168       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1169       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1171       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1172       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1173
1174       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1175       // when we have a 256bit-wide blend with immediate.
1176       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1177
1178       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1183       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1184       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1185
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1190       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1191       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1192     } else {
1193       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1197
1198       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1202
1203       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1205       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1207
1208       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1209       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1210       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1211       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1212       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1213       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1214       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1215       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1216       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1217       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1218       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1219       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1220     }
1221
1222     // In the customized shift lowering, the legal cases in AVX2 will be
1223     // recognized.
1224     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1226
1227     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1228     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1229
1230     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1231     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1232
1233     // Custom lower several nodes for 256-bit types.
1234     for (MVT VT : MVT::vector_valuetypes()) {
1235       if (VT.getScalarSizeInBits() >= 32) {
1236         setOperationAction(ISD::MLOAD,  VT, Legal);
1237         setOperationAction(ISD::MSTORE, VT, Legal);
1238       }
1239       // Extract subvector is special because the value type
1240       // (result) is 128-bit but the source is 256-bit wide.
1241       if (VT.is128BitVector()) {
1242         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1243       }
1244       // Do not attempt to custom lower other non-256-bit vectors
1245       if (!VT.is256BitVector())
1246         continue;
1247
1248       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1249       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1250       setOperationAction(ISD::VSELECT,            VT, Custom);
1251       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1252       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1253       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1254       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1255       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1256     }
1257
1258     if (Subtarget->hasInt256())
1259       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1260
1261
1262     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1263     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1264       MVT VT = (MVT::SimpleValueType)i;
1265
1266       // Do not attempt to promote non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::AND,    VT, Promote);
1271       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1272       setOperationAction(ISD::OR,     VT, Promote);
1273       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1274       setOperationAction(ISD::XOR,    VT, Promote);
1275       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1276       setOperationAction(ISD::LOAD,   VT, Promote);
1277       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1278       setOperationAction(ISD::SELECT, VT, Promote);
1279       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1280     }
1281   }
1282
1283   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1284     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1285     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1286     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1287     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1288
1289     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1290     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1291     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1292
1293     for (MVT VT : MVT::fp_vector_valuetypes())
1294       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1295
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1298     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1299     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1300     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1301     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1302     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1303     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1304     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1305     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1306     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1307     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1308
1309     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1310     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1311     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1312     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1313     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1314     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1315     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1316     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1317     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1322
1323     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1329
1330     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1331     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1335     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1336     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1337     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1338
1339     // FIXME:  [US]INT_TO_FP are not legal for f80.
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1341     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1342     if (Subtarget->is64Bit()) {
1343       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1344       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1345     }
1346     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1347     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1349     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1352     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1360     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1361     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1362
1363     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1364     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1365     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1366     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1367     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1368     if (Subtarget->hasVLX()){
1369       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1370       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1371       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1372       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1373       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1374
1375       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1376       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1377       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1378       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1379       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1380     }
1381     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1382     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1384     if (Subtarget->hasDQI()) {
1385       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1386       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1387
1388       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1389       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1390       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1391       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1392       if (Subtarget->hasVLX()) {
1393         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1394         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1395         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1396         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1397         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1398         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1399         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1400         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1401       }
1402     }
1403     if (Subtarget->hasVLX()) {
1404       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1405       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1406       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1408       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1409       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1411       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1412     }
1413     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1414     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1415     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1416     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1417     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1418     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1419     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1420     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1422     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1423     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1424     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1425     if (Subtarget->hasDQI()) {
1426       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1427       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1428     }
1429     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1430     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1431     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1432     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1433     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1434     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1435     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1436     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1437     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1438     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1439
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1461     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1462
1463     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1464     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1465     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1466     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1467     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1468     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1469     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1470     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1471
1472     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1473     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1474
1475     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1476     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1477
1478     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1479
1480     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1481     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1482
1483     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1484     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1485
1486     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1487     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1488
1489     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1490     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1491     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1492     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1493     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1494     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1495
1496     if (Subtarget->hasCDI()) {
1497       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1498       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1499       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1500       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1501     }
1502     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1503       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1504       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1505       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1506       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1507       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1508       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1509       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1510       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1511     }
1512     if (Subtarget->hasDQI()) {
1513       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1514       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1515       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1516     }
1517     // Custom lower several nodes.
1518     for (MVT VT : MVT::vector_valuetypes()) {
1519       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1520       if (EltSize == 1) {
1521         setOperationAction(ISD::AND, VT, Legal);
1522         setOperationAction(ISD::OR,  VT, Legal);
1523         setOperationAction(ISD::XOR,  VT, Legal);
1524       }
1525       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1526         setOperationAction(ISD::MGATHER,  VT, Custom);
1527         setOperationAction(ISD::MSCATTER, VT, Custom);
1528       }
1529       // Extract subvector is special because the value type
1530       // (result) is 256/128-bit but the source is 512-bit wide.
1531       if (VT.is128BitVector() || VT.is256BitVector()) {
1532         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1533       }
1534       if (VT.getVectorElementType() == MVT::i1)
1535         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1536
1537       // Do not attempt to custom lower other non-512-bit vectors
1538       if (!VT.is512BitVector())
1539         continue;
1540
1541       if (EltSize >= 32) {
1542         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1543         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1544         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1545         setOperationAction(ISD::VSELECT,             VT, Legal);
1546         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1547         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1548         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1549         setOperationAction(ISD::MLOAD,               VT, Legal);
1550         setOperationAction(ISD::MSTORE,              VT, Legal);
1551       }
1552     }
1553     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1554       MVT VT = (MVT::SimpleValueType)i;
1555
1556       // Do not attempt to promote non-512-bit vectors.
1557       if (!VT.is512BitVector())
1558         continue;
1559
1560       setOperationAction(ISD::SELECT, VT, Promote);
1561       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1562     }
1563   }// has  AVX-512
1564
1565   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1566     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1567     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1568
1569     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1570     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1571
1572     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1573     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1574     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1575     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1576     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1577     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1578     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1579     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1580     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1581     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1582     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1583     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1584     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1585     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1586     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1587     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1588     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1589     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1590     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1591     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1592     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1593     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1594     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1595     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1596     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1597     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1598     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1599     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1600     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1601     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1602     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1603
1604     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1605     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1606     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1607     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1608     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1609     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1610     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1611     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1612
1613     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1614     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1615     if (Subtarget->hasVLX())
1616       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1617
1618     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1619       const MVT VT = (MVT::SimpleValueType)i;
1620
1621       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1622
1623       // Do not attempt to promote non-512-bit vectors.
1624       if (!VT.is512BitVector())
1625         continue;
1626
1627       if (EltSize < 32) {
1628         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1629         setOperationAction(ISD::VSELECT,             VT, Legal);
1630       }
1631     }
1632   }
1633
1634   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1635     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1636     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1637
1638     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1639     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1641     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1644     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1645     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1646     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1647     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1648
1649     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1650     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1651     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1652     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1653     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1654     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1655     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1656     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1657
1658     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1659     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1660     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1661     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1662     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1663     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1664     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1665     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1666   }
1667
1668   // We want to custom lower some of our intrinsics.
1669   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1670   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1671   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1672   if (!Subtarget->is64Bit())
1673     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1674
1675   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1676   // handle type legalization for these operations here.
1677   //
1678   // FIXME: We really should do custom legalization for addition and
1679   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1680   // than generic legalization for 64-bit multiplication-with-overflow, though.
1681   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1682     // Add/Sub/Mul with overflow operations are custom lowered.
1683     MVT VT = IntVTs[i];
1684     setOperationAction(ISD::SADDO, VT, Custom);
1685     setOperationAction(ISD::UADDO, VT, Custom);
1686     setOperationAction(ISD::SSUBO, VT, Custom);
1687     setOperationAction(ISD::USUBO, VT, Custom);
1688     setOperationAction(ISD::SMULO, VT, Custom);
1689     setOperationAction(ISD::UMULO, VT, Custom);
1690   }
1691
1692
1693   if (!Subtarget->is64Bit()) {
1694     // These libcalls are not available in 32-bit.
1695     setLibcallName(RTLIB::SHL_I128, nullptr);
1696     setLibcallName(RTLIB::SRL_I128, nullptr);
1697     setLibcallName(RTLIB::SRA_I128, nullptr);
1698   }
1699
1700   // Combine sin / cos into one node or libcall if possible.
1701   if (Subtarget->hasSinCos()) {
1702     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1703     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1704     if (Subtarget->isTargetDarwin()) {
1705       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1706       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1707       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1708       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1709     }
1710   }
1711
1712   if (Subtarget->isTargetWin64()) {
1713     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1714     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1715     setOperationAction(ISD::SREM, MVT::i128, Custom);
1716     setOperationAction(ISD::UREM, MVT::i128, Custom);
1717     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1718     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1719   }
1720
1721   // We have target-specific dag combine patterns for the following nodes:
1722   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1723   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1724   setTargetDAGCombine(ISD::BITCAST);
1725   setTargetDAGCombine(ISD::VSELECT);
1726   setTargetDAGCombine(ISD::SELECT);
1727   setTargetDAGCombine(ISD::SHL);
1728   setTargetDAGCombine(ISD::SRA);
1729   setTargetDAGCombine(ISD::SRL);
1730   setTargetDAGCombine(ISD::OR);
1731   setTargetDAGCombine(ISD::AND);
1732   setTargetDAGCombine(ISD::ADD);
1733   setTargetDAGCombine(ISD::FADD);
1734   setTargetDAGCombine(ISD::FSUB);
1735   setTargetDAGCombine(ISD::FMA);
1736   setTargetDAGCombine(ISD::SUB);
1737   setTargetDAGCombine(ISD::LOAD);
1738   setTargetDAGCombine(ISD::MLOAD);
1739   setTargetDAGCombine(ISD::STORE);
1740   setTargetDAGCombine(ISD::MSTORE);
1741   setTargetDAGCombine(ISD::ZERO_EXTEND);
1742   setTargetDAGCombine(ISD::ANY_EXTEND);
1743   setTargetDAGCombine(ISD::SIGN_EXTEND);
1744   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1745   setTargetDAGCombine(ISD::SINT_TO_FP);
1746   setTargetDAGCombine(ISD::UINT_TO_FP);
1747   setTargetDAGCombine(ISD::SETCC);
1748   setTargetDAGCombine(ISD::BUILD_VECTOR);
1749   setTargetDAGCombine(ISD::MUL);
1750   setTargetDAGCombine(ISD::XOR);
1751
1752   computeRegisterProperties(Subtarget->getRegisterInfo());
1753
1754   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1755   MaxStoresPerMemsetOptSize = 8;
1756   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1757   MaxStoresPerMemcpyOptSize = 4;
1758   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1759   MaxStoresPerMemmoveOptSize = 4;
1760   setPrefLoopAlignment(4); // 2^4 bytes.
1761
1762   // Predictable cmov don't hurt on atom because it's in-order.
1763   PredictableSelectIsExpensive = !Subtarget->isAtom();
1764   EnableExtLdPromotion = true;
1765   setPrefFunctionAlignment(4); // 2^4 bytes.
1766
1767   verifyIntrinsicTables();
1768 }
1769
1770 // This has so far only been implemented for 64-bit MachO.
1771 bool X86TargetLowering::useLoadStackGuardNode() const {
1772   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1773 }
1774
1775 TargetLoweringBase::LegalizeTypeAction
1776 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1777   if (ExperimentalVectorWideningLegalization &&
1778       VT.getVectorNumElements() != 1 &&
1779       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1780     return TypeWidenVector;
1781
1782   return TargetLoweringBase::getPreferredVectorAction(VT);
1783 }
1784
1785 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1786                                           EVT VT) const {
1787   if (!VT.isVector())
1788     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1789
1790   const unsigned NumElts = VT.getVectorNumElements();
1791   const EVT EltVT = VT.getVectorElementType();
1792   if (VT.is512BitVector()) {
1793     if (Subtarget->hasAVX512())
1794       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1795           EltVT == MVT::f32 || EltVT == MVT::f64)
1796         switch(NumElts) {
1797         case  8: return MVT::v8i1;
1798         case 16: return MVT::v16i1;
1799       }
1800     if (Subtarget->hasBWI())
1801       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1802         switch(NumElts) {
1803         case 32: return MVT::v32i1;
1804         case 64: return MVT::v64i1;
1805       }
1806   }
1807
1808   if (VT.is256BitVector() || VT.is128BitVector()) {
1809     if (Subtarget->hasVLX())
1810       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1811           EltVT == MVT::f32 || EltVT == MVT::f64)
1812         switch(NumElts) {
1813         case 2: return MVT::v2i1;
1814         case 4: return MVT::v4i1;
1815         case 8: return MVT::v8i1;
1816       }
1817     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1818       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1819         switch(NumElts) {
1820         case  8: return MVT::v8i1;
1821         case 16: return MVT::v16i1;
1822         case 32: return MVT::v32i1;
1823       }
1824   }
1825
1826   return VT.changeVectorElementTypeToInteger();
1827 }
1828
1829 /// Helper for getByValTypeAlignment to determine
1830 /// the desired ByVal argument alignment.
1831 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1832   if (MaxAlign == 16)
1833     return;
1834   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1835     if (VTy->getBitWidth() == 128)
1836       MaxAlign = 16;
1837   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1838     unsigned EltAlign = 0;
1839     getMaxByValAlign(ATy->getElementType(), EltAlign);
1840     if (EltAlign > MaxAlign)
1841       MaxAlign = EltAlign;
1842   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1843     for (auto *EltTy : STy->elements()) {
1844       unsigned EltAlign = 0;
1845       getMaxByValAlign(EltTy, EltAlign);
1846       if (EltAlign > MaxAlign)
1847         MaxAlign = EltAlign;
1848       if (MaxAlign == 16)
1849         break;
1850     }
1851   }
1852 }
1853
1854 /// Return the desired alignment for ByVal aggregate
1855 /// function arguments in the caller parameter area. For X86, aggregates
1856 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1857 /// are at 4-byte boundaries.
1858 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1859                                                   const DataLayout &DL) const {
1860   if (Subtarget->is64Bit()) {
1861     // Max of 8 and alignment of type.
1862     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1863     if (TyAlign > 8)
1864       return TyAlign;
1865     return 8;
1866   }
1867
1868   unsigned Align = 4;
1869   if (Subtarget->hasSSE1())
1870     getMaxByValAlign(Ty, Align);
1871   return Align;
1872 }
1873
1874 /// Returns the target specific optimal type for load
1875 /// and store operations as a result of memset, memcpy, and memmove
1876 /// lowering. If DstAlign is zero that means it's safe to destination
1877 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1878 /// means there isn't a need to check it against alignment requirement,
1879 /// probably because the source does not need to be loaded. If 'IsMemset' is
1880 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1881 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1882 /// source is constant so it does not need to be loaded.
1883 /// It returns EVT::Other if the type should be determined using generic
1884 /// target-independent logic.
1885 EVT
1886 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1887                                        unsigned DstAlign, unsigned SrcAlign,
1888                                        bool IsMemset, bool ZeroMemset,
1889                                        bool MemcpyStrSrc,
1890                                        MachineFunction &MF) const {
1891   const Function *F = MF.getFunction();
1892   if ((!IsMemset || ZeroMemset) &&
1893       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1894     if (Size >= 16 &&
1895         (!Subtarget->isUnalignedMem16Slow() ||
1896          ((DstAlign == 0 || DstAlign >= 16) &&
1897           (SrcAlign == 0 || SrcAlign >= 16)))) {
1898       if (Size >= 32) {
1899         // FIXME: Check if unaligned 32-byte accesses are slow.
1900         if (Subtarget->hasInt256())
1901           return MVT::v8i32;
1902         if (Subtarget->hasFp256())
1903           return MVT::v8f32;
1904       }
1905       if (Subtarget->hasSSE2())
1906         return MVT::v4i32;
1907       if (Subtarget->hasSSE1())
1908         return MVT::v4f32;
1909     } else if (!MemcpyStrSrc && Size >= 8 &&
1910                !Subtarget->is64Bit() &&
1911                Subtarget->hasSSE2()) {
1912       // Do not use f64 to lower memcpy if source is string constant. It's
1913       // better to use i32 to avoid the loads.
1914       return MVT::f64;
1915     }
1916   }
1917   // This is a compromise. If we reach here, unaligned accesses may be slow on
1918   // this target. However, creating smaller, aligned accesses could be even
1919   // slower and would certainly be a lot more code.
1920   if (Subtarget->is64Bit() && Size >= 8)
1921     return MVT::i64;
1922   return MVT::i32;
1923 }
1924
1925 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1926   if (VT == MVT::f32)
1927     return X86ScalarSSEf32;
1928   else if (VT == MVT::f64)
1929     return X86ScalarSSEf64;
1930   return true;
1931 }
1932
1933 bool
1934 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1935                                                   unsigned,
1936                                                   unsigned,
1937                                                   bool *Fast) const {
1938   if (Fast) {
1939     switch (VT.getSizeInBits()) {
1940     default:
1941       // 8-byte and under are always assumed to be fast.
1942       *Fast = true;
1943       break;
1944     case 128:
1945       *Fast = !Subtarget->isUnalignedMem16Slow();
1946       break;
1947     case 256:
1948       *Fast = !Subtarget->isUnalignedMem32Slow();
1949       break;
1950     // TODO: What about AVX-512 (512-bit) accesses?
1951     }
1952   }
1953   // Misaligned accesses of any size are always allowed.
1954   return true;
1955 }
1956
1957 /// Return the entry encoding for a jump table in the
1958 /// current function.  The returned value is a member of the
1959 /// MachineJumpTableInfo::JTEntryKind enum.
1960 unsigned X86TargetLowering::getJumpTableEncoding() const {
1961   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1962   // symbol.
1963   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1964       Subtarget->isPICStyleGOT())
1965     return MachineJumpTableInfo::EK_Custom32;
1966
1967   // Otherwise, use the normal jump table encoding heuristics.
1968   return TargetLowering::getJumpTableEncoding();
1969 }
1970
1971 bool X86TargetLowering::useSoftFloat() const {
1972   return Subtarget->useSoftFloat();
1973 }
1974
1975 const MCExpr *
1976 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1977                                              const MachineBasicBlock *MBB,
1978                                              unsigned uid,MCContext &Ctx) const{
1979   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1980          Subtarget->isPICStyleGOT());
1981   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1982   // entries.
1983   return MCSymbolRefExpr::create(MBB->getSymbol(),
1984                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1985 }
1986
1987 /// Returns relocation base for the given PIC jumptable.
1988 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1989                                                     SelectionDAG &DAG) const {
1990   if (!Subtarget->is64Bit())
1991     // This doesn't have SDLoc associated with it, but is not really the
1992     // same as a Register.
1993     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1994                        getPointerTy(DAG.getDataLayout()));
1995   return Table;
1996 }
1997
1998 /// This returns the relocation base for the given PIC jumptable,
1999 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2000 const MCExpr *X86TargetLowering::
2001 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2002                              MCContext &Ctx) const {
2003   // X86-64 uses RIP relative addressing based on the jump table label.
2004   if (Subtarget->isPICStyleRIPRel())
2005     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2006
2007   // Otherwise, the reference is relative to the PIC base.
2008   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2009 }
2010
2011 std::pair<const TargetRegisterClass *, uint8_t>
2012 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2013                                            MVT VT) const {
2014   const TargetRegisterClass *RRC = nullptr;
2015   uint8_t Cost = 1;
2016   switch (VT.SimpleTy) {
2017   default:
2018     return TargetLowering::findRepresentativeClass(TRI, VT);
2019   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2020     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2021     break;
2022   case MVT::x86mmx:
2023     RRC = &X86::VR64RegClass;
2024     break;
2025   case MVT::f32: case MVT::f64:
2026   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2027   case MVT::v4f32: case MVT::v2f64:
2028   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2029   case MVT::v4f64:
2030     RRC = &X86::VR128RegClass;
2031     break;
2032   }
2033   return std::make_pair(RRC, Cost);
2034 }
2035
2036 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2037                                                unsigned &Offset) const {
2038   if (!Subtarget->isTargetLinux())
2039     return false;
2040
2041   if (Subtarget->is64Bit()) {
2042     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2043     Offset = 0x28;
2044     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2045       AddressSpace = 256;
2046     else
2047       AddressSpace = 257;
2048   } else {
2049     // %gs:0x14 on i386
2050     Offset = 0x14;
2051     AddressSpace = 256;
2052   }
2053   return true;
2054 }
2055
2056 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2057                                             unsigned DestAS) const {
2058   assert(SrcAS != DestAS && "Expected different address spaces!");
2059
2060   return SrcAS < 256 && DestAS < 256;
2061 }
2062
2063 //===----------------------------------------------------------------------===//
2064 //               Return Value Calling Convention Implementation
2065 //===----------------------------------------------------------------------===//
2066
2067 #include "X86GenCallingConv.inc"
2068
2069 bool
2070 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2071                                   MachineFunction &MF, bool isVarArg,
2072                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2073                         LLVMContext &Context) const {
2074   SmallVector<CCValAssign, 16> RVLocs;
2075   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2076   return CCInfo.CheckReturn(Outs, RetCC_X86);
2077 }
2078
2079 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2080   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2081   return ScratchRegs;
2082 }
2083
2084 SDValue
2085 X86TargetLowering::LowerReturn(SDValue Chain,
2086                                CallingConv::ID CallConv, bool isVarArg,
2087                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2088                                const SmallVectorImpl<SDValue> &OutVals,
2089                                SDLoc dl, SelectionDAG &DAG) const {
2090   MachineFunction &MF = DAG.getMachineFunction();
2091   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2092
2093   SmallVector<CCValAssign, 16> RVLocs;
2094   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2095   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2096
2097   SDValue Flag;
2098   SmallVector<SDValue, 6> RetOps;
2099   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2100   // Operand #1 = Bytes To Pop
2101   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2102                    MVT::i16));
2103
2104   // Copy the result values into the output registers.
2105   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2106     CCValAssign &VA = RVLocs[i];
2107     assert(VA.isRegLoc() && "Can only return in registers!");
2108     SDValue ValToCopy = OutVals[i];
2109     EVT ValVT = ValToCopy.getValueType();
2110
2111     // Promote values to the appropriate types.
2112     if (VA.getLocInfo() == CCValAssign::SExt)
2113       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2114     else if (VA.getLocInfo() == CCValAssign::ZExt)
2115       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2116     else if (VA.getLocInfo() == CCValAssign::AExt) {
2117       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2118         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2119       else
2120         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2121     }
2122     else if (VA.getLocInfo() == CCValAssign::BCvt)
2123       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2124
2125     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2126            "Unexpected FP-extend for return value.");
2127
2128     // If this is x86-64, and we disabled SSE, we can't return FP values,
2129     // or SSE or MMX vectors.
2130     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2131          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2132           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2133       report_fatal_error("SSE register return with SSE disabled");
2134     }
2135     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2136     // llvm-gcc has never done it right and no one has noticed, so this
2137     // should be OK for now.
2138     if (ValVT == MVT::f64 &&
2139         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2140       report_fatal_error("SSE2 register return with SSE2 disabled");
2141
2142     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2143     // the RET instruction and handled by the FP Stackifier.
2144     if (VA.getLocReg() == X86::FP0 ||
2145         VA.getLocReg() == X86::FP1) {
2146       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2147       // change the value to the FP stack register class.
2148       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2149         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2150       RetOps.push_back(ValToCopy);
2151       // Don't emit a copytoreg.
2152       continue;
2153     }
2154
2155     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2156     // which is returned in RAX / RDX.
2157     if (Subtarget->is64Bit()) {
2158       if (ValVT == MVT::x86mmx) {
2159         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2160           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2161           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2162                                   ValToCopy);
2163           // If we don't have SSE2 available, convert to v4f32 so the generated
2164           // register is legal.
2165           if (!Subtarget->hasSSE2())
2166             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2167         }
2168       }
2169     }
2170
2171     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2172     Flag = Chain.getValue(1);
2173     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2174   }
2175
2176   // All x86 ABIs require that for returning structs by value we copy
2177   // the sret argument into %rax/%eax (depending on ABI) for the return.
2178   // We saved the argument into a virtual register in the entry block,
2179   // so now we copy the value out and into %rax/%eax.
2180   //
2181   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2182   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2183   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2184   // either case FuncInfo->setSRetReturnReg() will have been called.
2185   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2186     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2187                                      getPointerTy(MF.getDataLayout()));
2188
2189     unsigned RetValReg
2190         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2191           X86::RAX : X86::EAX;
2192     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2193     Flag = Chain.getValue(1);
2194
2195     // RAX/EAX now acts like a return value.
2196     RetOps.push_back(
2197         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2198   }
2199
2200   RetOps[0] = Chain;  // Update chain.
2201
2202   // Add the flag if we have it.
2203   if (Flag.getNode())
2204     RetOps.push_back(Flag);
2205
2206   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2207 }
2208
2209 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2210   if (N->getNumValues() != 1)
2211     return false;
2212   if (!N->hasNUsesOfValue(1, 0))
2213     return false;
2214
2215   SDValue TCChain = Chain;
2216   SDNode *Copy = *N->use_begin();
2217   if (Copy->getOpcode() == ISD::CopyToReg) {
2218     // If the copy has a glue operand, we conservatively assume it isn't safe to
2219     // perform a tail call.
2220     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2221       return false;
2222     TCChain = Copy->getOperand(0);
2223   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2224     return false;
2225
2226   bool HasRet = false;
2227   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2228        UI != UE; ++UI) {
2229     if (UI->getOpcode() != X86ISD::RET_FLAG)
2230       return false;
2231     // If we are returning more than one value, we can definitely
2232     // not make a tail call see PR19530
2233     if (UI->getNumOperands() > 4)
2234       return false;
2235     if (UI->getNumOperands() == 4 &&
2236         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2237       return false;
2238     HasRet = true;
2239   }
2240
2241   if (!HasRet)
2242     return false;
2243
2244   Chain = TCChain;
2245   return true;
2246 }
2247
2248 EVT
2249 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2250                                             ISD::NodeType ExtendKind) const {
2251   MVT ReturnMVT;
2252   // TODO: Is this also valid on 32-bit?
2253   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2254     ReturnMVT = MVT::i8;
2255   else
2256     ReturnMVT = MVT::i32;
2257
2258   EVT MinVT = getRegisterType(Context, ReturnMVT);
2259   return VT.bitsLT(MinVT) ? MinVT : VT;
2260 }
2261
2262 /// Lower the result values of a call into the
2263 /// appropriate copies out of appropriate physical registers.
2264 ///
2265 SDValue
2266 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2267                                    CallingConv::ID CallConv, bool isVarArg,
2268                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2269                                    SDLoc dl, SelectionDAG &DAG,
2270                                    SmallVectorImpl<SDValue> &InVals) const {
2271
2272   // Assign locations to each value returned by this call.
2273   SmallVector<CCValAssign, 16> RVLocs;
2274   bool Is64Bit = Subtarget->is64Bit();
2275   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2276                  *DAG.getContext());
2277   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2278
2279   // Copy all of the result registers out of their specified physreg.
2280   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2281     CCValAssign &VA = RVLocs[i];
2282     EVT CopyVT = VA.getLocVT();
2283
2284     // If this is x86-64, and we disabled SSE, we can't return FP values
2285     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2286         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2287       report_fatal_error("SSE register return with SSE disabled");
2288     }
2289
2290     // If we prefer to use the value in xmm registers, copy it out as f80 and
2291     // use a truncate to move it from fp stack reg to xmm reg.
2292     bool RoundAfterCopy = false;
2293     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2294         isScalarFPTypeInSSEReg(VA.getValVT())) {
2295       CopyVT = MVT::f80;
2296       RoundAfterCopy = (CopyVT != VA.getLocVT());
2297     }
2298
2299     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2300                                CopyVT, InFlag).getValue(1);
2301     SDValue Val = Chain.getValue(0);
2302
2303     if (RoundAfterCopy)
2304       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2305                         // This truncation won't change the value.
2306                         DAG.getIntPtrConstant(1, dl));
2307
2308     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2309       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2310
2311     InFlag = Chain.getValue(2);
2312     InVals.push_back(Val);
2313   }
2314
2315   return Chain;
2316 }
2317
2318 //===----------------------------------------------------------------------===//
2319 //                C & StdCall & Fast Calling Convention implementation
2320 //===----------------------------------------------------------------------===//
2321 //  StdCall calling convention seems to be standard for many Windows' API
2322 //  routines and around. It differs from C calling convention just a little:
2323 //  callee should clean up the stack, not caller. Symbols should be also
2324 //  decorated in some fancy way :) It doesn't support any vector arguments.
2325 //  For info on fast calling convention see Fast Calling Convention (tail call)
2326 //  implementation LowerX86_32FastCCCallTo.
2327
2328 /// CallIsStructReturn - Determines whether a call uses struct return
2329 /// semantics.
2330 enum StructReturnType {
2331   NotStructReturn,
2332   RegStructReturn,
2333   StackStructReturn
2334 };
2335 static StructReturnType
2336 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2337   if (Outs.empty())
2338     return NotStructReturn;
2339
2340   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2341   if (!Flags.isSRet())
2342     return NotStructReturn;
2343   if (Flags.isInReg())
2344     return RegStructReturn;
2345   return StackStructReturn;
2346 }
2347
2348 /// Determines whether a function uses struct return semantics.
2349 static StructReturnType
2350 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2351   if (Ins.empty())
2352     return NotStructReturn;
2353
2354   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2355   if (!Flags.isSRet())
2356     return NotStructReturn;
2357   if (Flags.isInReg())
2358     return RegStructReturn;
2359   return StackStructReturn;
2360 }
2361
2362 /// Make a copy of an aggregate at address specified by "Src" to address
2363 /// "Dst" with size and alignment information specified by the specific
2364 /// parameter attribute. The copy will be passed as a byval function parameter.
2365 static SDValue
2366 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2367                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2368                           SDLoc dl) {
2369   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2370
2371   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2372                        /*isVolatile*/false, /*AlwaysInline=*/true,
2373                        /*isTailCall*/false,
2374                        MachinePointerInfo(), MachinePointerInfo());
2375 }
2376
2377 /// Return true if the calling convention is one that
2378 /// supports tail call optimization.
2379 static bool IsTailCallConvention(CallingConv::ID CC) {
2380   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2381           CC == CallingConv::HiPE);
2382 }
2383
2384 /// \brief Return true if the calling convention is a C calling convention.
2385 static bool IsCCallConvention(CallingConv::ID CC) {
2386   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2387           CC == CallingConv::X86_64_SysV);
2388 }
2389
2390 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2391   auto Attr =
2392       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2393   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2394     return false;
2395
2396   CallSite CS(CI);
2397   CallingConv::ID CalleeCC = CS.getCallingConv();
2398   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2399     return false;
2400
2401   return true;
2402 }
2403
2404 /// Return true if the function is being made into
2405 /// a tailcall target by changing its ABI.
2406 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2407                                    bool GuaranteedTailCallOpt) {
2408   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2409 }
2410
2411 SDValue
2412 X86TargetLowering::LowerMemArgument(SDValue Chain,
2413                                     CallingConv::ID CallConv,
2414                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2415                                     SDLoc dl, SelectionDAG &DAG,
2416                                     const CCValAssign &VA,
2417                                     MachineFrameInfo *MFI,
2418                                     unsigned i) const {
2419   // Create the nodes corresponding to a load from this parameter slot.
2420   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2421   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2422       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2423   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2424   EVT ValVT;
2425
2426   // If value is passed by pointer we have address passed instead of the value
2427   // itself.
2428   bool ExtendedInMem = VA.isExtInLoc() &&
2429     VA.getValVT().getScalarType() == MVT::i1;
2430
2431   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2432     ValVT = VA.getLocVT();
2433   else
2434     ValVT = VA.getValVT();
2435
2436   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2437   // changed with more analysis.
2438   // In case of tail call optimization mark all arguments mutable. Since they
2439   // could be overwritten by lowering of arguments in case of a tail call.
2440   if (Flags.isByVal()) {
2441     unsigned Bytes = Flags.getByValSize();
2442     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2443     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2444     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2445   } else {
2446     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2447                                     VA.getLocMemOffset(), isImmutable);
2448     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2449     SDValue Val = DAG.getLoad(
2450         ValVT, dl, Chain, FIN,
2451         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2452         false, false, 0);
2453     return ExtendedInMem ?
2454       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2455   }
2456 }
2457
2458 // FIXME: Get this from tablegen.
2459 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2460                                                 const X86Subtarget *Subtarget) {
2461   assert(Subtarget->is64Bit());
2462
2463   if (Subtarget->isCallingConvWin64(CallConv)) {
2464     static const MCPhysReg GPR64ArgRegsWin64[] = {
2465       X86::RCX, X86::RDX, X86::R8,  X86::R9
2466     };
2467     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2468   }
2469
2470   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2471     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2472   };
2473   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2474 }
2475
2476 // FIXME: Get this from tablegen.
2477 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2478                                                 CallingConv::ID CallConv,
2479                                                 const X86Subtarget *Subtarget) {
2480   assert(Subtarget->is64Bit());
2481   if (Subtarget->isCallingConvWin64(CallConv)) {
2482     // The XMM registers which might contain var arg parameters are shadowed
2483     // in their paired GPR.  So we only need to save the GPR to their home
2484     // slots.
2485     // TODO: __vectorcall will change this.
2486     return None;
2487   }
2488
2489   const Function *Fn = MF.getFunction();
2490   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2491   bool isSoftFloat = Subtarget->useSoftFloat();
2492   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2493          "SSE register cannot be used when SSE is disabled!");
2494   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2495     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2496     // registers.
2497     return None;
2498
2499   static const MCPhysReg XMMArgRegs64Bit[] = {
2500     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2501     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2502   };
2503   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2504 }
2505
2506 SDValue
2507 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2508                                         CallingConv::ID CallConv,
2509                                         bool isVarArg,
2510                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2511                                         SDLoc dl,
2512                                         SelectionDAG &DAG,
2513                                         SmallVectorImpl<SDValue> &InVals)
2514                                           const {
2515   MachineFunction &MF = DAG.getMachineFunction();
2516   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2517   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2518
2519   const Function* Fn = MF.getFunction();
2520   if (Fn->hasExternalLinkage() &&
2521       Subtarget->isTargetCygMing() &&
2522       Fn->getName() == "main")
2523     FuncInfo->setForceFramePointer(true);
2524
2525   MachineFrameInfo *MFI = MF.getFrameInfo();
2526   bool Is64Bit = Subtarget->is64Bit();
2527   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2528
2529   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2530          "Var args not supported with calling convention fastcc, ghc or hipe");
2531
2532   // Assign locations to all of the incoming arguments.
2533   SmallVector<CCValAssign, 16> ArgLocs;
2534   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2535
2536   // Allocate shadow area for Win64
2537   if (IsWin64)
2538     CCInfo.AllocateStack(32, 8);
2539
2540   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2541
2542   unsigned LastVal = ~0U;
2543   SDValue ArgValue;
2544   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2545     CCValAssign &VA = ArgLocs[i];
2546     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2547     // places.
2548     assert(VA.getValNo() != LastVal &&
2549            "Don't support value assigned to multiple locs yet");
2550     (void)LastVal;
2551     LastVal = VA.getValNo();
2552
2553     if (VA.isRegLoc()) {
2554       EVT RegVT = VA.getLocVT();
2555       const TargetRegisterClass *RC;
2556       if (RegVT == MVT::i32)
2557         RC = &X86::GR32RegClass;
2558       else if (Is64Bit && RegVT == MVT::i64)
2559         RC = &X86::GR64RegClass;
2560       else if (RegVT == MVT::f32)
2561         RC = &X86::FR32RegClass;
2562       else if (RegVT == MVT::f64)
2563         RC = &X86::FR64RegClass;
2564       else if (RegVT.is512BitVector())
2565         RC = &X86::VR512RegClass;
2566       else if (RegVT.is256BitVector())
2567         RC = &X86::VR256RegClass;
2568       else if (RegVT.is128BitVector())
2569         RC = &X86::VR128RegClass;
2570       else if (RegVT == MVT::x86mmx)
2571         RC = &X86::VR64RegClass;
2572       else if (RegVT == MVT::i1)
2573         RC = &X86::VK1RegClass;
2574       else if (RegVT == MVT::v8i1)
2575         RC = &X86::VK8RegClass;
2576       else if (RegVT == MVT::v16i1)
2577         RC = &X86::VK16RegClass;
2578       else if (RegVT == MVT::v32i1)
2579         RC = &X86::VK32RegClass;
2580       else if (RegVT == MVT::v64i1)
2581         RC = &X86::VK64RegClass;
2582       else
2583         llvm_unreachable("Unknown argument type!");
2584
2585       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2586       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2587
2588       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2589       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2590       // right size.
2591       if (VA.getLocInfo() == CCValAssign::SExt)
2592         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2593                                DAG.getValueType(VA.getValVT()));
2594       else if (VA.getLocInfo() == CCValAssign::ZExt)
2595         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2596                                DAG.getValueType(VA.getValVT()));
2597       else if (VA.getLocInfo() == CCValAssign::BCvt)
2598         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2599
2600       if (VA.isExtInLoc()) {
2601         // Handle MMX values passed in XMM regs.
2602         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2603           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2604         else
2605           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2606       }
2607     } else {
2608       assert(VA.isMemLoc());
2609       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2610     }
2611
2612     // If value is passed via pointer - do a load.
2613     if (VA.getLocInfo() == CCValAssign::Indirect)
2614       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2615                              MachinePointerInfo(), false, false, false, 0);
2616
2617     InVals.push_back(ArgValue);
2618   }
2619
2620   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2621     // All x86 ABIs require that for returning structs by value we copy the
2622     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2623     // the argument into a virtual register so that we can access it from the
2624     // return points.
2625     if (Ins[i].Flags.isSRet()) {
2626       unsigned Reg = FuncInfo->getSRetReturnReg();
2627       if (!Reg) {
2628         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2629         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2630         FuncInfo->setSRetReturnReg(Reg);
2631       }
2632       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2633       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2634       break;
2635     }
2636   }
2637
2638   unsigned StackSize = CCInfo.getNextStackOffset();
2639   // Align stack specially for tail calls.
2640   if (FuncIsMadeTailCallSafe(CallConv,
2641                              MF.getTarget().Options.GuaranteedTailCallOpt))
2642     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2643
2644   // If the function takes variable number of arguments, make a frame index for
2645   // the start of the first vararg value... for expansion of llvm.va_start. We
2646   // can skip this if there are no va_start calls.
2647   if (MFI->hasVAStart() &&
2648       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2649                    CallConv != CallingConv::X86_ThisCall))) {
2650     FuncInfo->setVarArgsFrameIndex(
2651         MFI->CreateFixedObject(1, StackSize, true));
2652   }
2653
2654   MachineModuleInfo &MMI = MF.getMMI();
2655   const Function *WinEHParent = nullptr;
2656   if (MMI.hasWinEHFuncInfo(Fn))
2657     WinEHParent = MMI.getWinEHParent(Fn);
2658   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2659   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2660
2661   // Figure out if XMM registers are in use.
2662   assert(!(Subtarget->useSoftFloat() &&
2663            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2664          "SSE register cannot be used when SSE is disabled!");
2665
2666   // 64-bit calling conventions support varargs and register parameters, so we
2667   // have to do extra work to spill them in the prologue.
2668   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2669     // Find the first unallocated argument registers.
2670     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2671     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2672     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2673     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2674     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2675            "SSE register cannot be used when SSE is disabled!");
2676
2677     // Gather all the live in physical registers.
2678     SmallVector<SDValue, 6> LiveGPRs;
2679     SmallVector<SDValue, 8> LiveXMMRegs;
2680     SDValue ALVal;
2681     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2682       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2683       LiveGPRs.push_back(
2684           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2685     }
2686     if (!ArgXMMs.empty()) {
2687       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2688       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2689       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2690         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2691         LiveXMMRegs.push_back(
2692             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2693       }
2694     }
2695
2696     if (IsWin64) {
2697       // Get to the caller-allocated home save location.  Add 8 to account
2698       // for the return address.
2699       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2700       FuncInfo->setRegSaveFrameIndex(
2701           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2702       // Fixup to set vararg frame on shadow area (4 x i64).
2703       if (NumIntRegs < 4)
2704         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2705     } else {
2706       // For X86-64, if there are vararg parameters that are passed via
2707       // registers, then we must store them to their spots on the stack so
2708       // they may be loaded by deferencing the result of va_next.
2709       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2710       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2711       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2712           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2713     }
2714
2715     // Store the integer parameter registers.
2716     SmallVector<SDValue, 8> MemOps;
2717     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2718                                       getPointerTy(DAG.getDataLayout()));
2719     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2720     for (SDValue Val : LiveGPRs) {
2721       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2722                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2723       SDValue Store =
2724           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2725                        MachinePointerInfo::getFixedStack(
2726                            DAG.getMachineFunction(),
2727                            FuncInfo->getRegSaveFrameIndex(), Offset),
2728                        false, false, 0);
2729       MemOps.push_back(Store);
2730       Offset += 8;
2731     }
2732
2733     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2734       // Now store the XMM (fp + vector) parameter registers.
2735       SmallVector<SDValue, 12> SaveXMMOps;
2736       SaveXMMOps.push_back(Chain);
2737       SaveXMMOps.push_back(ALVal);
2738       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2739                              FuncInfo->getRegSaveFrameIndex(), dl));
2740       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2741                              FuncInfo->getVarArgsFPOffset(), dl));
2742       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2743                         LiveXMMRegs.end());
2744       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2745                                    MVT::Other, SaveXMMOps));
2746     }
2747
2748     if (!MemOps.empty())
2749       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2750   } else if (IsWin64 && IsWinEHOutlined) {
2751     // Get to the caller-allocated home save location.  Add 8 to account
2752     // for the return address.
2753     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2754     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2755         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2756
2757     MMI.getWinEHFuncInfo(Fn)
2758         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2759         FuncInfo->getRegSaveFrameIndex();
2760
2761     // Store the second integer parameter (rdx) into rsp+16 relative to the
2762     // stack pointer at the entry of the function.
2763     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2764                                       getPointerTy(DAG.getDataLayout()));
2765     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2766     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2767     Chain = DAG.getStore(
2768         Val.getValue(1), dl, Val, RSFIN,
2769         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2770                                           FuncInfo->getRegSaveFrameIndex()),
2771         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2772   }
2773
2774   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2775     // Find the largest legal vector type.
2776     MVT VecVT = MVT::Other;
2777     // FIXME: Only some x86_32 calling conventions support AVX512.
2778     if (Subtarget->hasAVX512() &&
2779         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2780                      CallConv == CallingConv::Intel_OCL_BI)))
2781       VecVT = MVT::v16f32;
2782     else if (Subtarget->hasAVX())
2783       VecVT = MVT::v8f32;
2784     else if (Subtarget->hasSSE2())
2785       VecVT = MVT::v4f32;
2786
2787     // We forward some GPRs and some vector types.
2788     SmallVector<MVT, 2> RegParmTypes;
2789     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2790     RegParmTypes.push_back(IntVT);
2791     if (VecVT != MVT::Other)
2792       RegParmTypes.push_back(VecVT);
2793
2794     // Compute the set of forwarded registers. The rest are scratch.
2795     SmallVectorImpl<ForwardedRegister> &Forwards =
2796         FuncInfo->getForwardedMustTailRegParms();
2797     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2798
2799     // Conservatively forward AL on x86_64, since it might be used for varargs.
2800     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2801       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2802       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2803     }
2804
2805     // Copy all forwards from physical to virtual registers.
2806     for (ForwardedRegister &F : Forwards) {
2807       // FIXME: Can we use a less constrained schedule?
2808       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2809       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2810       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2811     }
2812   }
2813
2814   // Some CCs need callee pop.
2815   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2816                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2817     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2818   } else {
2819     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2820     // If this is an sret function, the return should pop the hidden pointer.
2821     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2822         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2823         argsAreStructReturn(Ins) == StackStructReturn)
2824       FuncInfo->setBytesToPopOnReturn(4);
2825   }
2826
2827   if (!Is64Bit) {
2828     // RegSaveFrameIndex is X86-64 only.
2829     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2830     if (CallConv == CallingConv::X86_FastCall ||
2831         CallConv == CallingConv::X86_ThisCall)
2832       // fastcc functions can't have varargs.
2833       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2834   }
2835
2836   FuncInfo->setArgumentStackSize(StackSize);
2837
2838   if (IsWinEHParent) {
2839     if (Is64Bit) {
2840       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2841       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2842       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2843       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2844       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2845                            MachinePointerInfo::getFixedStack(
2846                                DAG.getMachineFunction(), UnwindHelpFI),
2847                            /*isVolatile=*/true,
2848                            /*isNonTemporal=*/false, /*Alignment=*/0);
2849     } else {
2850       // Functions using Win32 EH are considered to have opaque SP adjustments
2851       // to force local variables to be addressed from the frame or base
2852       // pointers.
2853       MFI->setHasOpaqueSPAdjustment(true);
2854     }
2855   }
2856
2857   return Chain;
2858 }
2859
2860 SDValue
2861 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2862                                     SDValue StackPtr, SDValue Arg,
2863                                     SDLoc dl, SelectionDAG &DAG,
2864                                     const CCValAssign &VA,
2865                                     ISD::ArgFlagsTy Flags) const {
2866   unsigned LocMemOffset = VA.getLocMemOffset();
2867   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2868   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2869                        StackPtr, PtrOff);
2870   if (Flags.isByVal())
2871     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2872
2873   return DAG.getStore(
2874       Chain, dl, Arg, PtrOff,
2875       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2876       false, false, 0);
2877 }
2878
2879 /// Emit a load of return address if tail call
2880 /// optimization is performed and it is required.
2881 SDValue
2882 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2883                                            SDValue &OutRetAddr, SDValue Chain,
2884                                            bool IsTailCall, bool Is64Bit,
2885                                            int FPDiff, SDLoc dl) const {
2886   // Adjust the Return address stack slot.
2887   EVT VT = getPointerTy(DAG.getDataLayout());
2888   OutRetAddr = getReturnAddressFrameIndex(DAG);
2889
2890   // Load the "old" Return address.
2891   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2892                            false, false, false, 0);
2893   return SDValue(OutRetAddr.getNode(), 1);
2894 }
2895
2896 /// Emit a store of the return address if tail call
2897 /// optimization is performed and it is required (FPDiff!=0).
2898 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2899                                         SDValue Chain, SDValue RetAddrFrIdx,
2900                                         EVT PtrVT, unsigned SlotSize,
2901                                         int FPDiff, SDLoc dl) {
2902   // Store the return address to the appropriate stack slot.
2903   if (!FPDiff) return Chain;
2904   // Calculate the new stack slot for the return address.
2905   int NewReturnAddrFI =
2906     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2907                                          false);
2908   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2909   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2910                        MachinePointerInfo::getFixedStack(
2911                            DAG.getMachineFunction(), NewReturnAddrFI),
2912                        false, false, 0);
2913   return Chain;
2914 }
2915
2916 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2917 /// operation of specified width.
2918 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2919                        SDValue V2) {
2920   unsigned NumElems = VT.getVectorNumElements();
2921   SmallVector<int, 8> Mask;
2922   Mask.push_back(NumElems);
2923   for (unsigned i = 1; i != NumElems; ++i)
2924     Mask.push_back(i);
2925   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2926 }
2927
2928 SDValue
2929 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2930                              SmallVectorImpl<SDValue> &InVals) const {
2931   SelectionDAG &DAG                     = CLI.DAG;
2932   SDLoc &dl                             = CLI.DL;
2933   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2934   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2935   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2936   SDValue Chain                         = CLI.Chain;
2937   SDValue Callee                        = CLI.Callee;
2938   CallingConv::ID CallConv              = CLI.CallConv;
2939   bool &isTailCall                      = CLI.IsTailCall;
2940   bool isVarArg                         = CLI.IsVarArg;
2941
2942   MachineFunction &MF = DAG.getMachineFunction();
2943   bool Is64Bit        = Subtarget->is64Bit();
2944   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2945   StructReturnType SR = callIsStructReturn(Outs);
2946   bool IsSibcall      = false;
2947   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2948   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2949
2950   if (Attr.getValueAsString() == "true")
2951     isTailCall = false;
2952
2953   if (Subtarget->isPICStyleGOT() &&
2954       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2955     // If we are using a GOT, disable tail calls to external symbols with
2956     // default visibility. Tail calling such a symbol requires using a GOT
2957     // relocation, which forces early binding of the symbol. This breaks code
2958     // that require lazy function symbol resolution. Using musttail or
2959     // GuaranteedTailCallOpt will override this.
2960     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2961     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2962                G->getGlobal()->hasDefaultVisibility()))
2963       isTailCall = false;
2964   }
2965
2966   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2967   if (IsMustTail) {
2968     // Force this to be a tail call.  The verifier rules are enough to ensure
2969     // that we can lower this successfully without moving the return address
2970     // around.
2971     isTailCall = true;
2972   } else if (isTailCall) {
2973     // Check if it's really possible to do a tail call.
2974     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2975                     isVarArg, SR != NotStructReturn,
2976                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2977                     Outs, OutVals, Ins, DAG);
2978
2979     // Sibcalls are automatically detected tailcalls which do not require
2980     // ABI changes.
2981     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2982       IsSibcall = true;
2983
2984     if (isTailCall)
2985       ++NumTailCalls;
2986   }
2987
2988   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2989          "Var args not supported with calling convention fastcc, ghc or hipe");
2990
2991   // Analyze operands of the call, assigning locations to each operand.
2992   SmallVector<CCValAssign, 16> ArgLocs;
2993   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2994
2995   // Allocate shadow area for Win64
2996   if (IsWin64)
2997     CCInfo.AllocateStack(32, 8);
2998
2999   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3000
3001   // Get a count of how many bytes are to be pushed on the stack.
3002   unsigned NumBytes = CCInfo.getNextStackOffset();
3003   if (IsSibcall)
3004     // This is a sibcall. The memory operands are available in caller's
3005     // own caller's stack.
3006     NumBytes = 0;
3007   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3008            IsTailCallConvention(CallConv))
3009     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3010
3011   int FPDiff = 0;
3012   if (isTailCall && !IsSibcall && !IsMustTail) {
3013     // Lower arguments at fp - stackoffset + fpdiff.
3014     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3015
3016     FPDiff = NumBytesCallerPushed - NumBytes;
3017
3018     // Set the delta of movement of the returnaddr stackslot.
3019     // But only set if delta is greater than previous delta.
3020     if (FPDiff < X86Info->getTCReturnAddrDelta())
3021       X86Info->setTCReturnAddrDelta(FPDiff);
3022   }
3023
3024   unsigned NumBytesToPush = NumBytes;
3025   unsigned NumBytesToPop = NumBytes;
3026
3027   // If we have an inalloca argument, all stack space has already been allocated
3028   // for us and be right at the top of the stack.  We don't support multiple
3029   // arguments passed in memory when using inalloca.
3030   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3031     NumBytesToPush = 0;
3032     if (!ArgLocs.back().isMemLoc())
3033       report_fatal_error("cannot use inalloca attribute on a register "
3034                          "parameter");
3035     if (ArgLocs.back().getLocMemOffset() != 0)
3036       report_fatal_error("any parameter with the inalloca attribute must be "
3037                          "the only memory argument");
3038   }
3039
3040   if (!IsSibcall)
3041     Chain = DAG.getCALLSEQ_START(
3042         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3043
3044   SDValue RetAddrFrIdx;
3045   // Load return address for tail calls.
3046   if (isTailCall && FPDiff)
3047     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3048                                     Is64Bit, FPDiff, dl);
3049
3050   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3051   SmallVector<SDValue, 8> MemOpChains;
3052   SDValue StackPtr;
3053
3054   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3055   // of tail call optimization arguments are handle later.
3056   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3057   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3058     // Skip inalloca arguments, they have already been written.
3059     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3060     if (Flags.isInAlloca())
3061       continue;
3062
3063     CCValAssign &VA = ArgLocs[i];
3064     EVT RegVT = VA.getLocVT();
3065     SDValue Arg = OutVals[i];
3066     bool isByVal = Flags.isByVal();
3067
3068     // Promote the value if needed.
3069     switch (VA.getLocInfo()) {
3070     default: llvm_unreachable("Unknown loc info!");
3071     case CCValAssign::Full: break;
3072     case CCValAssign::SExt:
3073       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3074       break;
3075     case CCValAssign::ZExt:
3076       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3077       break;
3078     case CCValAssign::AExt:
3079       if (Arg.getValueType().isVector() &&
3080           Arg.getValueType().getScalarType() == MVT::i1)
3081         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3082       else if (RegVT.is128BitVector()) {
3083         // Special case: passing MMX values in XMM registers.
3084         Arg = DAG.getBitcast(MVT::i64, Arg);
3085         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3086         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3087       } else
3088         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3089       break;
3090     case CCValAssign::BCvt:
3091       Arg = DAG.getBitcast(RegVT, Arg);
3092       break;
3093     case CCValAssign::Indirect: {
3094       // Store the argument.
3095       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3096       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3097       Chain = DAG.getStore(
3098           Chain, dl, Arg, SpillSlot,
3099           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3100           false, false, 0);
3101       Arg = SpillSlot;
3102       break;
3103     }
3104     }
3105
3106     if (VA.isRegLoc()) {
3107       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3108       if (isVarArg && IsWin64) {
3109         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3110         // shadow reg if callee is a varargs function.
3111         unsigned ShadowReg = 0;
3112         switch (VA.getLocReg()) {
3113         case X86::XMM0: ShadowReg = X86::RCX; break;
3114         case X86::XMM1: ShadowReg = X86::RDX; break;
3115         case X86::XMM2: ShadowReg = X86::R8; break;
3116         case X86::XMM3: ShadowReg = X86::R9; break;
3117         }
3118         if (ShadowReg)
3119           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3120       }
3121     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3122       assert(VA.isMemLoc());
3123       if (!StackPtr.getNode())
3124         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3125                                       getPointerTy(DAG.getDataLayout()));
3126       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3127                                              dl, DAG, VA, Flags));
3128     }
3129   }
3130
3131   if (!MemOpChains.empty())
3132     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3133
3134   if (Subtarget->isPICStyleGOT()) {
3135     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3136     // GOT pointer.
3137     if (!isTailCall) {
3138       RegsToPass.push_back(std::make_pair(
3139           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3140                                           getPointerTy(DAG.getDataLayout()))));
3141     } else {
3142       // If we are tail calling and generating PIC/GOT style code load the
3143       // address of the callee into ECX. The value in ecx is used as target of
3144       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3145       // for tail calls on PIC/GOT architectures. Normally we would just put the
3146       // address of GOT into ebx and then call target@PLT. But for tail calls
3147       // ebx would be restored (since ebx is callee saved) before jumping to the
3148       // target@PLT.
3149
3150       // Note: The actual moving to ECX is done further down.
3151       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3152       if (G && !G->getGlobal()->hasLocalLinkage() &&
3153           G->getGlobal()->hasDefaultVisibility())
3154         Callee = LowerGlobalAddress(Callee, DAG);
3155       else if (isa<ExternalSymbolSDNode>(Callee))
3156         Callee = LowerExternalSymbol(Callee, DAG);
3157     }
3158   }
3159
3160   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3161     // From AMD64 ABI document:
3162     // For calls that may call functions that use varargs or stdargs
3163     // (prototype-less calls or calls to functions containing ellipsis (...) in
3164     // the declaration) %al is used as hidden argument to specify the number
3165     // of SSE registers used. The contents of %al do not need to match exactly
3166     // the number of registers, but must be an ubound on the number of SSE
3167     // registers used and is in the range 0 - 8 inclusive.
3168
3169     // Count the number of XMM registers allocated.
3170     static const MCPhysReg XMMArgRegs[] = {
3171       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3172       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3173     };
3174     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3175     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3176            && "SSE registers cannot be used when SSE is disabled");
3177
3178     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3179                                         DAG.getConstant(NumXMMRegs, dl,
3180                                                         MVT::i8)));
3181   }
3182
3183   if (isVarArg && IsMustTail) {
3184     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3185     for (const auto &F : Forwards) {
3186       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3187       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3188     }
3189   }
3190
3191   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3192   // don't need this because the eligibility check rejects calls that require
3193   // shuffling arguments passed in memory.
3194   if (!IsSibcall && isTailCall) {
3195     // Force all the incoming stack arguments to be loaded from the stack
3196     // before any new outgoing arguments are stored to the stack, because the
3197     // outgoing stack slots may alias the incoming argument stack slots, and
3198     // the alias isn't otherwise explicit. This is slightly more conservative
3199     // than necessary, because it means that each store effectively depends
3200     // on every argument instead of just those arguments it would clobber.
3201     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3202
3203     SmallVector<SDValue, 8> MemOpChains2;
3204     SDValue FIN;
3205     int FI = 0;
3206     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3207       CCValAssign &VA = ArgLocs[i];
3208       if (VA.isRegLoc())
3209         continue;
3210       assert(VA.isMemLoc());
3211       SDValue Arg = OutVals[i];
3212       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3213       // Skip inalloca arguments.  They don't require any work.
3214       if (Flags.isInAlloca())
3215         continue;
3216       // Create frame index.
3217       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3218       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3219       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3220       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3221
3222       if (Flags.isByVal()) {
3223         // Copy relative to framepointer.
3224         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3225         if (!StackPtr.getNode())
3226           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3227                                         getPointerTy(DAG.getDataLayout()));
3228         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3229                              StackPtr, Source);
3230
3231         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3232                                                          ArgChain,
3233                                                          Flags, DAG, dl));
3234       } else {
3235         // Store relative to framepointer.
3236         MemOpChains2.push_back(DAG.getStore(
3237             ArgChain, dl, Arg, FIN,
3238             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3239             false, false, 0));
3240       }
3241     }
3242
3243     if (!MemOpChains2.empty())
3244       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3245
3246     // Store the return address to the appropriate stack slot.
3247     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3248                                      getPointerTy(DAG.getDataLayout()),
3249                                      RegInfo->getSlotSize(), FPDiff, dl);
3250   }
3251
3252   // Build a sequence of copy-to-reg nodes chained together with token chain
3253   // and flag operands which copy the outgoing args into registers.
3254   SDValue InFlag;
3255   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3256     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3257                              RegsToPass[i].second, InFlag);
3258     InFlag = Chain.getValue(1);
3259   }
3260
3261   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3262     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3263     // In the 64-bit large code model, we have to make all calls
3264     // through a register, since the call instruction's 32-bit
3265     // pc-relative offset may not be large enough to hold the whole
3266     // address.
3267   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3268     // If the callee is a GlobalAddress node (quite common, every direct call
3269     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3270     // it.
3271     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3272
3273     // We should use extra load for direct calls to dllimported functions in
3274     // non-JIT mode.
3275     const GlobalValue *GV = G->getGlobal();
3276     if (!GV->hasDLLImportStorageClass()) {
3277       unsigned char OpFlags = 0;
3278       bool ExtraLoad = false;
3279       unsigned WrapperKind = ISD::DELETED_NODE;
3280
3281       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3282       // external symbols most go through the PLT in PIC mode.  If the symbol
3283       // has hidden or protected visibility, or if it is static or local, then
3284       // we don't need to use the PLT - we can directly call it.
3285       if (Subtarget->isTargetELF() &&
3286           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3287           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3288         OpFlags = X86II::MO_PLT;
3289       } else if (Subtarget->isPICStyleStubAny() &&
3290                  !GV->isStrongDefinitionForLinker() &&
3291                  (!Subtarget->getTargetTriple().isMacOSX() ||
3292                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3293         // PC-relative references to external symbols should go through $stub,
3294         // unless we're building with the leopard linker or later, which
3295         // automatically synthesizes these stubs.
3296         OpFlags = X86II::MO_DARWIN_STUB;
3297       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3298                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3299         // If the function is marked as non-lazy, generate an indirect call
3300         // which loads from the GOT directly. This avoids runtime overhead
3301         // at the cost of eager binding (and one extra byte of encoding).
3302         OpFlags = X86II::MO_GOTPCREL;
3303         WrapperKind = X86ISD::WrapperRIP;
3304         ExtraLoad = true;
3305       }
3306
3307       Callee = DAG.getTargetGlobalAddress(
3308           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3309
3310       // Add a wrapper if needed.
3311       if (WrapperKind != ISD::DELETED_NODE)
3312         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3313                              getPointerTy(DAG.getDataLayout()), Callee);
3314       // Add extra indirection if needed.
3315       if (ExtraLoad)
3316         Callee = DAG.getLoad(
3317             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3318             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3319             false, 0);
3320     }
3321   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3322     unsigned char OpFlags = 0;
3323
3324     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3325     // external symbols should go through the PLT.
3326     if (Subtarget->isTargetELF() &&
3327         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3328       OpFlags = X86II::MO_PLT;
3329     } else if (Subtarget->isPICStyleStubAny() &&
3330                (!Subtarget->getTargetTriple().isMacOSX() ||
3331                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3332       // PC-relative references to external symbols should go through $stub,
3333       // unless we're building with the leopard linker or later, which
3334       // automatically synthesizes these stubs.
3335       OpFlags = X86II::MO_DARWIN_STUB;
3336     }
3337
3338     Callee = DAG.getTargetExternalSymbol(
3339         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3340   } else if (Subtarget->isTarget64BitILP32() &&
3341              Callee->getValueType(0) == MVT::i32) {
3342     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3343     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3344   }
3345
3346   // Returns a chain & a flag for retval copy to use.
3347   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3348   SmallVector<SDValue, 8> Ops;
3349
3350   if (!IsSibcall && isTailCall) {
3351     Chain = DAG.getCALLSEQ_END(Chain,
3352                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3353                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3354     InFlag = Chain.getValue(1);
3355   }
3356
3357   Ops.push_back(Chain);
3358   Ops.push_back(Callee);
3359
3360   if (isTailCall)
3361     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3362
3363   // Add argument registers to the end of the list so that they are known live
3364   // into the call.
3365   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3366     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3367                                   RegsToPass[i].second.getValueType()));
3368
3369   // Add a register mask operand representing the call-preserved registers.
3370   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3371   assert(Mask && "Missing call preserved mask for calling convention");
3372
3373   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3374   // the function clobbers all registers. If an exception is thrown, the runtime
3375   // will not restore CSRs.
3376   // FIXME: Model this more precisely so that we can register allocate across
3377   // the normal edge and spill and fill across the exceptional edge.
3378   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3379     const Function *CallerFn = MF.getFunction();
3380     EHPersonality Pers =
3381         CallerFn->hasPersonalityFn()
3382             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3383             : EHPersonality::Unknown;
3384     if (isMSVCEHPersonality(Pers))
3385       Mask = RegInfo->getNoPreservedMask();
3386   }
3387
3388   Ops.push_back(DAG.getRegisterMask(Mask));
3389
3390   if (InFlag.getNode())
3391     Ops.push_back(InFlag);
3392
3393   if (isTailCall) {
3394     // We used to do:
3395     //// If this is the first return lowered for this function, add the regs
3396     //// to the liveout set for the function.
3397     // This isn't right, although it's probably harmless on x86; liveouts
3398     // should be computed from returns not tail calls.  Consider a void
3399     // function making a tail call to a function returning int.
3400     MF.getFrameInfo()->setHasTailCall();
3401     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3402   }
3403
3404   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3405   InFlag = Chain.getValue(1);
3406
3407   // Create the CALLSEQ_END node.
3408   unsigned NumBytesForCalleeToPop;
3409   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3410                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3411     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3412   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3413            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3414            SR == StackStructReturn)
3415     // If this is a call to a struct-return function, the callee
3416     // pops the hidden struct pointer, so we have to push it back.
3417     // This is common for Darwin/X86, Linux & Mingw32 targets.
3418     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3419     NumBytesForCalleeToPop = 4;
3420   else
3421     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3422
3423   // Returns a flag for retval copy to use.
3424   if (!IsSibcall) {
3425     Chain = DAG.getCALLSEQ_END(Chain,
3426                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3427                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3428                                                      true),
3429                                InFlag, dl);
3430     InFlag = Chain.getValue(1);
3431   }
3432
3433   // Handle result values, copying them out of physregs into vregs that we
3434   // return.
3435   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3436                          Ins, dl, DAG, InVals);
3437 }
3438
3439 //===----------------------------------------------------------------------===//
3440 //                Fast Calling Convention (tail call) implementation
3441 //===----------------------------------------------------------------------===//
3442
3443 //  Like std call, callee cleans arguments, convention except that ECX is
3444 //  reserved for storing the tail called function address. Only 2 registers are
3445 //  free for argument passing (inreg). Tail call optimization is performed
3446 //  provided:
3447 //                * tailcallopt is enabled
3448 //                * caller/callee are fastcc
3449 //  On X86_64 architecture with GOT-style position independent code only local
3450 //  (within module) calls are supported at the moment.
3451 //  To keep the stack aligned according to platform abi the function
3452 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3453 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3454 //  If a tail called function callee has more arguments than the caller the
3455 //  caller needs to make sure that there is room to move the RETADDR to. This is
3456 //  achieved by reserving an area the size of the argument delta right after the
3457 //  original RETADDR, but before the saved framepointer or the spilled registers
3458 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3459 //  stack layout:
3460 //    arg1
3461 //    arg2
3462 //    RETADDR
3463 //    [ new RETADDR
3464 //      move area ]
3465 //    (possible EBP)
3466 //    ESI
3467 //    EDI
3468 //    local1 ..
3469
3470 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3471 /// requirement.
3472 unsigned
3473 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3474                                                SelectionDAG& DAG) const {
3475   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3476   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3477   unsigned StackAlignment = TFI.getStackAlignment();
3478   uint64_t AlignMask = StackAlignment - 1;
3479   int64_t Offset = StackSize;
3480   unsigned SlotSize = RegInfo->getSlotSize();
3481   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3482     // Number smaller than 12 so just add the difference.
3483     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3484   } else {
3485     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3486     Offset = ((~AlignMask) & Offset) + StackAlignment +
3487       (StackAlignment-SlotSize);
3488   }
3489   return Offset;
3490 }
3491
3492 /// Return true if the given stack call argument is already available in the
3493 /// same position (relatively) of the caller's incoming argument stack.
3494 static
3495 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3496                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3497                          const X86InstrInfo *TII) {
3498   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3499   int FI = INT_MAX;
3500   if (Arg.getOpcode() == ISD::CopyFromReg) {
3501     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3502     if (!TargetRegisterInfo::isVirtualRegister(VR))
3503       return false;
3504     MachineInstr *Def = MRI->getVRegDef(VR);
3505     if (!Def)
3506       return false;
3507     if (!Flags.isByVal()) {
3508       if (!TII->isLoadFromStackSlot(Def, FI))
3509         return false;
3510     } else {
3511       unsigned Opcode = Def->getOpcode();
3512       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3513            Opcode == X86::LEA64_32r) &&
3514           Def->getOperand(1).isFI()) {
3515         FI = Def->getOperand(1).getIndex();
3516         Bytes = Flags.getByValSize();
3517       } else
3518         return false;
3519     }
3520   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3521     if (Flags.isByVal())
3522       // ByVal argument is passed in as a pointer but it's now being
3523       // dereferenced. e.g.
3524       // define @foo(%struct.X* %A) {
3525       //   tail call @bar(%struct.X* byval %A)
3526       // }
3527       return false;
3528     SDValue Ptr = Ld->getBasePtr();
3529     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3530     if (!FINode)
3531       return false;
3532     FI = FINode->getIndex();
3533   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3534     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3535     FI = FINode->getIndex();
3536     Bytes = Flags.getByValSize();
3537   } else
3538     return false;
3539
3540   assert(FI != INT_MAX);
3541   if (!MFI->isFixedObjectIndex(FI))
3542     return false;
3543   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3544 }
3545
3546 /// Check whether the call is eligible for tail call optimization. Targets
3547 /// that want to do tail call optimization should implement this function.
3548 bool
3549 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3550                                                      CallingConv::ID CalleeCC,
3551                                                      bool isVarArg,
3552                                                      bool isCalleeStructRet,
3553                                                      bool isCallerStructRet,
3554                                                      Type *RetTy,
3555                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3556                                     const SmallVectorImpl<SDValue> &OutVals,
3557                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3558                                                      SelectionDAG &DAG) const {
3559   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3560     return false;
3561
3562   // If -tailcallopt is specified, make fastcc functions tail-callable.
3563   const MachineFunction &MF = DAG.getMachineFunction();
3564   const Function *CallerF = MF.getFunction();
3565
3566   // If the function return type is x86_fp80 and the callee return type is not,
3567   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3568   // perform a tailcall optimization here.
3569   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3570     return false;
3571
3572   CallingConv::ID CallerCC = CallerF->getCallingConv();
3573   bool CCMatch = CallerCC == CalleeCC;
3574   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3575   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3576
3577   // Win64 functions have extra shadow space for argument homing. Don't do the
3578   // sibcall if the caller and callee have mismatched expectations for this
3579   // space.
3580   if (IsCalleeWin64 != IsCallerWin64)
3581     return false;
3582
3583   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3584     if (IsTailCallConvention(CalleeCC) && CCMatch)
3585       return true;
3586     return false;
3587   }
3588
3589   // Look for obvious safe cases to perform tail call optimization that do not
3590   // require ABI changes. This is what gcc calls sibcall.
3591
3592   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3593   // emit a special epilogue.
3594   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3595   if (RegInfo->needsStackRealignment(MF))
3596     return false;
3597
3598   // Also avoid sibcall optimization if either caller or callee uses struct
3599   // return semantics.
3600   if (isCalleeStructRet || isCallerStructRet)
3601     return false;
3602
3603   // An stdcall/thiscall caller is expected to clean up its arguments; the
3604   // callee isn't going to do that.
3605   // FIXME: this is more restrictive than needed. We could produce a tailcall
3606   // when the stack adjustment matches. For example, with a thiscall that takes
3607   // only one argument.
3608   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3609                    CallerCC == CallingConv::X86_ThisCall))
3610     return false;
3611
3612   // Do not sibcall optimize vararg calls unless all arguments are passed via
3613   // registers.
3614   if (isVarArg && !Outs.empty()) {
3615
3616     // Optimizing for varargs on Win64 is unlikely to be safe without
3617     // additional testing.
3618     if (IsCalleeWin64 || IsCallerWin64)
3619       return false;
3620
3621     SmallVector<CCValAssign, 16> ArgLocs;
3622     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3623                    *DAG.getContext());
3624
3625     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3626     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3627       if (!ArgLocs[i].isRegLoc())
3628         return false;
3629   }
3630
3631   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3632   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3633   // this into a sibcall.
3634   bool Unused = false;
3635   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3636     if (!Ins[i].Used) {
3637       Unused = true;
3638       break;
3639     }
3640   }
3641   if (Unused) {
3642     SmallVector<CCValAssign, 16> RVLocs;
3643     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3644                    *DAG.getContext());
3645     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3646     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3647       CCValAssign &VA = RVLocs[i];
3648       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3649         return false;
3650     }
3651   }
3652
3653   // If the calling conventions do not match, then we'd better make sure the
3654   // results are returned in the same way as what the caller expects.
3655   if (!CCMatch) {
3656     SmallVector<CCValAssign, 16> RVLocs1;
3657     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3658                     *DAG.getContext());
3659     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3660
3661     SmallVector<CCValAssign, 16> RVLocs2;
3662     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3663                     *DAG.getContext());
3664     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3665
3666     if (RVLocs1.size() != RVLocs2.size())
3667       return false;
3668     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3669       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3670         return false;
3671       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3672         return false;
3673       if (RVLocs1[i].isRegLoc()) {
3674         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3675           return false;
3676       } else {
3677         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3678           return false;
3679       }
3680     }
3681   }
3682
3683   // If the callee takes no arguments then go on to check the results of the
3684   // call.
3685   if (!Outs.empty()) {
3686     // Check if stack adjustment is needed. For now, do not do this if any
3687     // argument is passed on the stack.
3688     SmallVector<CCValAssign, 16> ArgLocs;
3689     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3690                    *DAG.getContext());
3691
3692     // Allocate shadow area for Win64
3693     if (IsCalleeWin64)
3694       CCInfo.AllocateStack(32, 8);
3695
3696     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3697     if (CCInfo.getNextStackOffset()) {
3698       MachineFunction &MF = DAG.getMachineFunction();
3699       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3700         return false;
3701
3702       // Check if the arguments are already laid out in the right way as
3703       // the caller's fixed stack objects.
3704       MachineFrameInfo *MFI = MF.getFrameInfo();
3705       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3706       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3707       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3708         CCValAssign &VA = ArgLocs[i];
3709         SDValue Arg = OutVals[i];
3710         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3711         if (VA.getLocInfo() == CCValAssign::Indirect)
3712           return false;
3713         if (!VA.isRegLoc()) {
3714           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3715                                    MFI, MRI, TII))
3716             return false;
3717         }
3718       }
3719     }
3720
3721     // If the tailcall address may be in a register, then make sure it's
3722     // possible to register allocate for it. In 32-bit, the call address can
3723     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3724     // callee-saved registers are restored. These happen to be the same
3725     // registers used to pass 'inreg' arguments so watch out for those.
3726     if (!Subtarget->is64Bit() &&
3727         ((!isa<GlobalAddressSDNode>(Callee) &&
3728           !isa<ExternalSymbolSDNode>(Callee)) ||
3729          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3730       unsigned NumInRegs = 0;
3731       // In PIC we need an extra register to formulate the address computation
3732       // for the callee.
3733       unsigned MaxInRegs =
3734         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3735
3736       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3737         CCValAssign &VA = ArgLocs[i];
3738         if (!VA.isRegLoc())
3739           continue;
3740         unsigned Reg = VA.getLocReg();
3741         switch (Reg) {
3742         default: break;
3743         case X86::EAX: case X86::EDX: case X86::ECX:
3744           if (++NumInRegs == MaxInRegs)
3745             return false;
3746           break;
3747         }
3748       }
3749     }
3750   }
3751
3752   return true;
3753 }
3754
3755 FastISel *
3756 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3757                                   const TargetLibraryInfo *libInfo) const {
3758   return X86::createFastISel(funcInfo, libInfo);
3759 }
3760
3761 //===----------------------------------------------------------------------===//
3762 //                           Other Lowering Hooks
3763 //===----------------------------------------------------------------------===//
3764
3765 static bool MayFoldLoad(SDValue Op) {
3766   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3767 }
3768
3769 static bool MayFoldIntoStore(SDValue Op) {
3770   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3771 }
3772
3773 static bool isTargetShuffle(unsigned Opcode) {
3774   switch(Opcode) {
3775   default: return false;
3776   case X86ISD::BLENDI:
3777   case X86ISD::PSHUFB:
3778   case X86ISD::PSHUFD:
3779   case X86ISD::PSHUFHW:
3780   case X86ISD::PSHUFLW:
3781   case X86ISD::SHUFP:
3782   case X86ISD::PALIGNR:
3783   case X86ISD::MOVLHPS:
3784   case X86ISD::MOVLHPD:
3785   case X86ISD::MOVHLPS:
3786   case X86ISD::MOVLPS:
3787   case X86ISD::MOVLPD:
3788   case X86ISD::MOVSHDUP:
3789   case X86ISD::MOVSLDUP:
3790   case X86ISD::MOVDDUP:
3791   case X86ISD::MOVSS:
3792   case X86ISD::MOVSD:
3793   case X86ISD::UNPCKL:
3794   case X86ISD::UNPCKH:
3795   case X86ISD::VPERMILPI:
3796   case X86ISD::VPERM2X128:
3797   case X86ISD::VPERMI:
3798   case X86ISD::VPERMV:
3799   case X86ISD::VPERMV3:
3800     return true;
3801   }
3802 }
3803
3804 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3805                                     SDValue V1, unsigned TargetMask,
3806                                     SelectionDAG &DAG) {
3807   switch(Opc) {
3808   default: llvm_unreachable("Unknown x86 shuffle node");
3809   case X86ISD::PSHUFD:
3810   case X86ISD::PSHUFHW:
3811   case X86ISD::PSHUFLW:
3812   case X86ISD::VPERMILPI:
3813   case X86ISD::VPERMI:
3814     return DAG.getNode(Opc, dl, VT, V1,
3815                        DAG.getConstant(TargetMask, dl, MVT::i8));
3816   }
3817 }
3818
3819 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3820                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3821   switch(Opc) {
3822   default: llvm_unreachable("Unknown x86 shuffle node");
3823   case X86ISD::MOVLHPS:
3824   case X86ISD::MOVLHPD:
3825   case X86ISD::MOVHLPS:
3826   case X86ISD::MOVLPS:
3827   case X86ISD::MOVLPD:
3828   case X86ISD::MOVSS:
3829   case X86ISD::MOVSD:
3830   case X86ISD::UNPCKL:
3831   case X86ISD::UNPCKH:
3832     return DAG.getNode(Opc, dl, VT, V1, V2);
3833   }
3834 }
3835
3836 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3837   MachineFunction &MF = DAG.getMachineFunction();
3838   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3839   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3840   int ReturnAddrIndex = FuncInfo->getRAIndex();
3841
3842   if (ReturnAddrIndex == 0) {
3843     // Set up a frame object for the return address.
3844     unsigned SlotSize = RegInfo->getSlotSize();
3845     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3846                                                            -(int64_t)SlotSize,
3847                                                            false);
3848     FuncInfo->setRAIndex(ReturnAddrIndex);
3849   }
3850
3851   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3852 }
3853
3854 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3855                                        bool hasSymbolicDisplacement) {
3856   // Offset should fit into 32 bit immediate field.
3857   if (!isInt<32>(Offset))
3858     return false;
3859
3860   // If we don't have a symbolic displacement - we don't have any extra
3861   // restrictions.
3862   if (!hasSymbolicDisplacement)
3863     return true;
3864
3865   // FIXME: Some tweaks might be needed for medium code model.
3866   if (M != CodeModel::Small && M != CodeModel::Kernel)
3867     return false;
3868
3869   // For small code model we assume that latest object is 16MB before end of 31
3870   // bits boundary. We may also accept pretty large negative constants knowing
3871   // that all objects are in the positive half of address space.
3872   if (M == CodeModel::Small && Offset < 16*1024*1024)
3873     return true;
3874
3875   // For kernel code model we know that all object resist in the negative half
3876   // of 32bits address space. We may not accept negative offsets, since they may
3877   // be just off and we may accept pretty large positive ones.
3878   if (M == CodeModel::Kernel && Offset >= 0)
3879     return true;
3880
3881   return false;
3882 }
3883
3884 /// Determines whether the callee is required to pop its own arguments.
3885 /// Callee pop is necessary to support tail calls.
3886 bool X86::isCalleePop(CallingConv::ID CallingConv,
3887                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3888   switch (CallingConv) {
3889   default:
3890     return false;
3891   case CallingConv::X86_StdCall:
3892   case CallingConv::X86_FastCall:
3893   case CallingConv::X86_ThisCall:
3894     return !is64Bit;
3895   case CallingConv::Fast:
3896   case CallingConv::GHC:
3897   case CallingConv::HiPE:
3898     if (IsVarArg)
3899       return false;
3900     return TailCallOpt;
3901   }
3902 }
3903
3904 /// \brief Return true if the condition is an unsigned comparison operation.
3905 static bool isX86CCUnsigned(unsigned X86CC) {
3906   switch (X86CC) {
3907   default: llvm_unreachable("Invalid integer condition!");
3908   case X86::COND_E:     return true;
3909   case X86::COND_G:     return false;
3910   case X86::COND_GE:    return false;
3911   case X86::COND_L:     return false;
3912   case X86::COND_LE:    return false;
3913   case X86::COND_NE:    return true;
3914   case X86::COND_B:     return true;
3915   case X86::COND_A:     return true;
3916   case X86::COND_BE:    return true;
3917   case X86::COND_AE:    return true;
3918   }
3919   llvm_unreachable("covered switch fell through?!");
3920 }
3921
3922 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3923 /// condition code, returning the condition code and the LHS/RHS of the
3924 /// comparison to make.
3925 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3926                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3927   if (!isFP) {
3928     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3929       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3930         // X > -1   -> X == 0, jump !sign.
3931         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3932         return X86::COND_NS;
3933       }
3934       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3935         // X < 0   -> X == 0, jump on sign.
3936         return X86::COND_S;
3937       }
3938       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3939         // X < 1   -> X <= 0
3940         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3941         return X86::COND_LE;
3942       }
3943     }
3944
3945     switch (SetCCOpcode) {
3946     default: llvm_unreachable("Invalid integer condition!");
3947     case ISD::SETEQ:  return X86::COND_E;
3948     case ISD::SETGT:  return X86::COND_G;
3949     case ISD::SETGE:  return X86::COND_GE;
3950     case ISD::SETLT:  return X86::COND_L;
3951     case ISD::SETLE:  return X86::COND_LE;
3952     case ISD::SETNE:  return X86::COND_NE;
3953     case ISD::SETULT: return X86::COND_B;
3954     case ISD::SETUGT: return X86::COND_A;
3955     case ISD::SETULE: return X86::COND_BE;
3956     case ISD::SETUGE: return X86::COND_AE;
3957     }
3958   }
3959
3960   // First determine if it is required or is profitable to flip the operands.
3961
3962   // If LHS is a foldable load, but RHS is not, flip the condition.
3963   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3964       !ISD::isNON_EXTLoad(RHS.getNode())) {
3965     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3966     std::swap(LHS, RHS);
3967   }
3968
3969   switch (SetCCOpcode) {
3970   default: break;
3971   case ISD::SETOLT:
3972   case ISD::SETOLE:
3973   case ISD::SETUGT:
3974   case ISD::SETUGE:
3975     std::swap(LHS, RHS);
3976     break;
3977   }
3978
3979   // On a floating point condition, the flags are set as follows:
3980   // ZF  PF  CF   op
3981   //  0 | 0 | 0 | X > Y
3982   //  0 | 0 | 1 | X < Y
3983   //  1 | 0 | 0 | X == Y
3984   //  1 | 1 | 1 | unordered
3985   switch (SetCCOpcode) {
3986   default: llvm_unreachable("Condcode should be pre-legalized away");
3987   case ISD::SETUEQ:
3988   case ISD::SETEQ:   return X86::COND_E;
3989   case ISD::SETOLT:              // flipped
3990   case ISD::SETOGT:
3991   case ISD::SETGT:   return X86::COND_A;
3992   case ISD::SETOLE:              // flipped
3993   case ISD::SETOGE:
3994   case ISD::SETGE:   return X86::COND_AE;
3995   case ISD::SETUGT:              // flipped
3996   case ISD::SETULT:
3997   case ISD::SETLT:   return X86::COND_B;
3998   case ISD::SETUGE:              // flipped
3999   case ISD::SETULE:
4000   case ISD::SETLE:   return X86::COND_BE;
4001   case ISD::SETONE:
4002   case ISD::SETNE:   return X86::COND_NE;
4003   case ISD::SETUO:   return X86::COND_P;
4004   case ISD::SETO:    return X86::COND_NP;
4005   case ISD::SETOEQ:
4006   case ISD::SETUNE:  return X86::COND_INVALID;
4007   }
4008 }
4009
4010 /// Is there a floating point cmov for the specific X86 condition code?
4011 /// Current x86 isa includes the following FP cmov instructions:
4012 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4013 static bool hasFPCMov(unsigned X86CC) {
4014   switch (X86CC) {
4015   default:
4016     return false;
4017   case X86::COND_B:
4018   case X86::COND_BE:
4019   case X86::COND_E:
4020   case X86::COND_P:
4021   case X86::COND_A:
4022   case X86::COND_AE:
4023   case X86::COND_NE:
4024   case X86::COND_NP:
4025     return true;
4026   }
4027 }
4028
4029 /// Returns true if the target can instruction select the
4030 /// specified FP immediate natively. If false, the legalizer will
4031 /// materialize the FP immediate as a load from a constant pool.
4032 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4033   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4034     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4035       return true;
4036   }
4037   return false;
4038 }
4039
4040 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4041                                               ISD::LoadExtType ExtTy,
4042                                               EVT NewVT) const {
4043   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4044   // relocation target a movq or addq instruction: don't let the load shrink.
4045   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4046   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4047     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4048       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4049   return true;
4050 }
4051
4052 /// \brief Returns true if it is beneficial to convert a load of a constant
4053 /// to just the constant itself.
4054 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4055                                                           Type *Ty) const {
4056   assert(Ty->isIntegerTy());
4057
4058   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4059   if (BitSize == 0 || BitSize > 64)
4060     return false;
4061   return true;
4062 }
4063
4064 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4065                                                 unsigned Index) const {
4066   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4067     return false;
4068
4069   return (Index == 0 || Index == ResVT.getVectorNumElements());
4070 }
4071
4072 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4073   // Speculate cttz only if we can directly use TZCNT.
4074   return Subtarget->hasBMI();
4075 }
4076
4077 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4078   // Speculate ctlz only if we can directly use LZCNT.
4079   return Subtarget->hasLZCNT();
4080 }
4081
4082 /// Return true if every element in Mask, beginning
4083 /// from position Pos and ending in Pos+Size is undef.
4084 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4085   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4086     if (0 <= Mask[i])
4087       return false;
4088   return true;
4089 }
4090
4091 /// Return true if Val is undef or if its value falls within the
4092 /// specified range (L, H].
4093 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4094   return (Val < 0) || (Val >= Low && Val < Hi);
4095 }
4096
4097 /// Val is either less than zero (undef) or equal to the specified value.
4098 static bool isUndefOrEqual(int Val, int CmpVal) {
4099   return (Val < 0 || Val == CmpVal);
4100 }
4101
4102 /// Return true if every element in Mask, beginning
4103 /// from position Pos and ending in Pos+Size, falls within the specified
4104 /// sequential range (Low, Low+Size]. or is undef.
4105 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4106                                        unsigned Pos, unsigned Size, int Low) {
4107   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4108     if (!isUndefOrEqual(Mask[i], Low))
4109       return false;
4110   return true;
4111 }
4112
4113 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4114 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4115 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4116   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4117   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4118     return false;
4119
4120   // The index should be aligned on a vecWidth-bit boundary.
4121   uint64_t Index =
4122     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4123
4124   MVT VT = N->getSimpleValueType(0);
4125   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4126   bool Result = (Index * ElSize) % vecWidth == 0;
4127
4128   return Result;
4129 }
4130
4131 /// Return true if the specified INSERT_SUBVECTOR
4132 /// operand specifies a subvector insert that is suitable for input to
4133 /// insertion of 128 or 256-bit subvectors
4134 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4135   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4136   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4137     return false;
4138   // The index should be aligned on a vecWidth-bit boundary.
4139   uint64_t Index =
4140     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4141
4142   MVT VT = N->getSimpleValueType(0);
4143   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4144   bool Result = (Index * ElSize) % vecWidth == 0;
4145
4146   return Result;
4147 }
4148
4149 bool X86::isVINSERT128Index(SDNode *N) {
4150   return isVINSERTIndex(N, 128);
4151 }
4152
4153 bool X86::isVINSERT256Index(SDNode *N) {
4154   return isVINSERTIndex(N, 256);
4155 }
4156
4157 bool X86::isVEXTRACT128Index(SDNode *N) {
4158   return isVEXTRACTIndex(N, 128);
4159 }
4160
4161 bool X86::isVEXTRACT256Index(SDNode *N) {
4162   return isVEXTRACTIndex(N, 256);
4163 }
4164
4165 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4166   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4167   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4168     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4169
4170   uint64_t Index =
4171     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4172
4173   MVT VecVT = N->getOperand(0).getSimpleValueType();
4174   MVT ElVT = VecVT.getVectorElementType();
4175
4176   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4177   return Index / NumElemsPerChunk;
4178 }
4179
4180 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4181   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4182   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4183     llvm_unreachable("Illegal insert subvector for VINSERT");
4184
4185   uint64_t Index =
4186     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4187
4188   MVT VecVT = N->getSimpleValueType(0);
4189   MVT ElVT = VecVT.getVectorElementType();
4190
4191   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4192   return Index / NumElemsPerChunk;
4193 }
4194
4195 /// Return the appropriate immediate to extract the specified
4196 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4197 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4198   return getExtractVEXTRACTImmediate(N, 128);
4199 }
4200
4201 /// Return the appropriate immediate to extract the specified
4202 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4203 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4204   return getExtractVEXTRACTImmediate(N, 256);
4205 }
4206
4207 /// Return the appropriate immediate to insert at the specified
4208 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4209 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4210   return getInsertVINSERTImmediate(N, 128);
4211 }
4212
4213 /// Return the appropriate immediate to insert at the specified
4214 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4215 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4216   return getInsertVINSERTImmediate(N, 256);
4217 }
4218
4219 /// Returns true if Elt is a constant integer zero
4220 static bool isZero(SDValue V) {
4221   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4222   return C && C->isNullValue();
4223 }
4224
4225 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4226 bool X86::isZeroNode(SDValue Elt) {
4227   if (isZero(Elt))
4228     return true;
4229   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4230     return CFP->getValueAPF().isPosZero();
4231   return false;
4232 }
4233
4234 /// Returns a vector of specified type with all zero elements.
4235 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4236                              SelectionDAG &DAG, SDLoc dl) {
4237   assert(VT.isVector() && "Expected a vector type");
4238
4239   // Always build SSE zero vectors as <4 x i32> bitcasted
4240   // to their dest type. This ensures they get CSE'd.
4241   SDValue Vec;
4242   if (VT.is128BitVector()) {  // SSE
4243     if (Subtarget->hasSSE2()) {  // SSE2
4244       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4245       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4246     } else { // SSE1
4247       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4248       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4249     }
4250   } else if (VT.is256BitVector()) { // AVX
4251     if (Subtarget->hasInt256()) { // AVX2
4252       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4253       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4254       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4255     } else {
4256       // 256-bit logic and arithmetic instructions in AVX are all
4257       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4258       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4259       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4260       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4261     }
4262   } else if (VT.is512BitVector()) { // AVX-512
4263       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4264       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4265                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4266       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4267   } else if (VT.getScalarType() == MVT::i1) {
4268
4269     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4270             && "Unexpected vector type");
4271     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4272             && "Unexpected vector type");
4273     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4274     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4275     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4276   } else
4277     llvm_unreachable("Unexpected vector type");
4278
4279   return DAG.getBitcast(VT, Vec);
4280 }
4281
4282 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4283                                 SelectionDAG &DAG, SDLoc dl,
4284                                 unsigned vectorWidth) {
4285   assert((vectorWidth == 128 || vectorWidth == 256) &&
4286          "Unsupported vector width");
4287   EVT VT = Vec.getValueType();
4288   EVT ElVT = VT.getVectorElementType();
4289   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4290   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4291                                   VT.getVectorNumElements()/Factor);
4292
4293   // Extract from UNDEF is UNDEF.
4294   if (Vec.getOpcode() == ISD::UNDEF)
4295     return DAG.getUNDEF(ResultVT);
4296
4297   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4298   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4299
4300   // This is the index of the first element of the vectorWidth-bit chunk
4301   // we want.
4302   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4303                                * ElemsPerChunk);
4304
4305   // If the input is a buildvector just emit a smaller one.
4306   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4307     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4308                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4309                                     ElemsPerChunk));
4310
4311   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4312   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4313 }
4314
4315 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4316 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4317 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4318 /// instructions or a simple subregister reference. Idx is an index in the
4319 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4320 /// lowering EXTRACT_VECTOR_ELT operations easier.
4321 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4322                                    SelectionDAG &DAG, SDLoc dl) {
4323   assert((Vec.getValueType().is256BitVector() ||
4324           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4325   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4326 }
4327
4328 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4329 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4330                                    SelectionDAG &DAG, SDLoc dl) {
4331   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4332   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4333 }
4334
4335 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4336                                unsigned IdxVal, SelectionDAG &DAG,
4337                                SDLoc dl, unsigned vectorWidth) {
4338   assert((vectorWidth == 128 || vectorWidth == 256) &&
4339          "Unsupported vector width");
4340   // Inserting UNDEF is Result
4341   if (Vec.getOpcode() == ISD::UNDEF)
4342     return Result;
4343   EVT VT = Vec.getValueType();
4344   EVT ElVT = VT.getVectorElementType();
4345   EVT ResultVT = Result.getValueType();
4346
4347   // Insert the relevant vectorWidth bits.
4348   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4349
4350   // This is the index of the first element of the vectorWidth-bit chunk
4351   // we want.
4352   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4353                                * ElemsPerChunk);
4354
4355   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4356   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4357 }
4358
4359 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4360 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4361 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4362 /// simple superregister reference.  Idx is an index in the 128 bits
4363 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4364 /// lowering INSERT_VECTOR_ELT operations easier.
4365 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4366                                   SelectionDAG &DAG, SDLoc dl) {
4367   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4368
4369   // For insertion into the zero index (low half) of a 256-bit vector, it is
4370   // more efficient to generate a blend with immediate instead of an insert*128.
4371   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4372   // extend the subvector to the size of the result vector. Make sure that
4373   // we are not recursing on that node by checking for undef here.
4374   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4375       Result.getOpcode() != ISD::UNDEF) {
4376     EVT ResultVT = Result.getValueType();
4377     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4378     SDValue Undef = DAG.getUNDEF(ResultVT);
4379     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4380                                  Vec, ZeroIndex);
4381
4382     // The blend instruction, and therefore its mask, depend on the data type.
4383     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4384     if (ScalarType.isFloatingPoint()) {
4385       // Choose either vblendps (float) or vblendpd (double).
4386       unsigned ScalarSize = ScalarType.getSizeInBits();
4387       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4388       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4389       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4390       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4391     }
4392
4393     const X86Subtarget &Subtarget =
4394     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4395
4396     // AVX2 is needed for 256-bit integer blend support.
4397     // Integers must be cast to 32-bit because there is only vpblendd;
4398     // vpblendw can't be used for this because it has a handicapped mask.
4399
4400     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4401     // is still more efficient than using the wrong domain vinsertf128 that
4402     // will be created by InsertSubVector().
4403     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4404
4405     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4406     Vec256 = DAG.getBitcast(CastVT, Vec256);
4407     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4408     return DAG.getBitcast(ResultVT, Vec256);
4409   }
4410
4411   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4412 }
4413
4414 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4415                                   SelectionDAG &DAG, SDLoc dl) {
4416   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4417   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4418 }
4419
4420 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4421 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4422 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4423 /// large BUILD_VECTORS.
4424 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4425                                    unsigned NumElems, SelectionDAG &DAG,
4426                                    SDLoc dl) {
4427   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4428   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4429 }
4430
4431 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4432                                    unsigned NumElems, SelectionDAG &DAG,
4433                                    SDLoc dl) {
4434   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4435   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4436 }
4437
4438 /// Returns a vector of specified type with all bits set.
4439 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4440 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4441 /// Then bitcast to their original type, ensuring they get CSE'd.
4442 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4443                              SDLoc dl) {
4444   assert(VT.isVector() && "Expected a vector type");
4445
4446   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4447   SDValue Vec;
4448   if (VT.is256BitVector()) {
4449     if (HasInt256) { // AVX2
4450       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4451       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4452     } else { // AVX
4453       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4454       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4455     }
4456   } else if (VT.is128BitVector()) {
4457     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4458   } else
4459     llvm_unreachable("Unexpected vector type");
4460
4461   return DAG.getBitcast(VT, Vec);
4462 }
4463
4464 /// Returns a vector_shuffle node for an unpackl operation.
4465 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4466                           SDValue V2) {
4467   unsigned NumElems = VT.getVectorNumElements();
4468   SmallVector<int, 8> Mask;
4469   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4470     Mask.push_back(i);
4471     Mask.push_back(i + NumElems);
4472   }
4473   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4474 }
4475
4476 /// Returns a vector_shuffle node for an unpackh operation.
4477 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4478                           SDValue V2) {
4479   unsigned NumElems = VT.getVectorNumElements();
4480   SmallVector<int, 8> Mask;
4481   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4482     Mask.push_back(i + Half);
4483     Mask.push_back(i + NumElems + Half);
4484   }
4485   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4486 }
4487
4488 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4489 /// This produces a shuffle where the low element of V2 is swizzled into the
4490 /// zero/undef vector, landing at element Idx.
4491 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4492 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4493                                            bool IsZero,
4494                                            const X86Subtarget *Subtarget,
4495                                            SelectionDAG &DAG) {
4496   MVT VT = V2.getSimpleValueType();
4497   SDValue V1 = IsZero
4498     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4499   unsigned NumElems = VT.getVectorNumElements();
4500   SmallVector<int, 16> MaskVec;
4501   for (unsigned i = 0; i != NumElems; ++i)
4502     // If this is the insertion idx, put the low elt of V2 here.
4503     MaskVec.push_back(i == Idx ? NumElems : i);
4504   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4505 }
4506
4507 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4508 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4509 /// uses one source. Note that this will set IsUnary for shuffles which use a
4510 /// single input multiple times, and in those cases it will
4511 /// adjust the mask to only have indices within that single input.
4512 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4513 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4514                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4515   unsigned NumElems = VT.getVectorNumElements();
4516   SDValue ImmN;
4517
4518   IsUnary = false;
4519   bool IsFakeUnary = false;
4520   switch(N->getOpcode()) {
4521   case X86ISD::BLENDI:
4522     ImmN = N->getOperand(N->getNumOperands()-1);
4523     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524     break;
4525   case X86ISD::SHUFP:
4526     ImmN = N->getOperand(N->getNumOperands()-1);
4527     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4528     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4529     break;
4530   case X86ISD::UNPCKH:
4531     DecodeUNPCKHMask(VT, Mask);
4532     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4533     break;
4534   case X86ISD::UNPCKL:
4535     DecodeUNPCKLMask(VT, Mask);
4536     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4537     break;
4538   case X86ISD::MOVHLPS:
4539     DecodeMOVHLPSMask(NumElems, Mask);
4540     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4541     break;
4542   case X86ISD::MOVLHPS:
4543     DecodeMOVLHPSMask(NumElems, Mask);
4544     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4545     break;
4546   case X86ISD::PALIGNR:
4547     ImmN = N->getOperand(N->getNumOperands()-1);
4548     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4549     break;
4550   case X86ISD::PSHUFD:
4551   case X86ISD::VPERMILPI:
4552     ImmN = N->getOperand(N->getNumOperands()-1);
4553     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4554     IsUnary = true;
4555     break;
4556   case X86ISD::PSHUFHW:
4557     ImmN = N->getOperand(N->getNumOperands()-1);
4558     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4559     IsUnary = true;
4560     break;
4561   case X86ISD::PSHUFLW:
4562     ImmN = N->getOperand(N->getNumOperands()-1);
4563     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4564     IsUnary = true;
4565     break;
4566   case X86ISD::PSHUFB: {
4567     IsUnary = true;
4568     SDValue MaskNode = N->getOperand(1);
4569     while (MaskNode->getOpcode() == ISD::BITCAST)
4570       MaskNode = MaskNode->getOperand(0);
4571
4572     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4573       // If we have a build-vector, then things are easy.
4574       EVT VT = MaskNode.getValueType();
4575       assert(VT.isVector() &&
4576              "Can't produce a non-vector with a build_vector!");
4577       if (!VT.isInteger())
4578         return false;
4579
4580       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4581
4582       SmallVector<uint64_t, 32> RawMask;
4583       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4584         SDValue Op = MaskNode->getOperand(i);
4585         if (Op->getOpcode() == ISD::UNDEF) {
4586           RawMask.push_back((uint64_t)SM_SentinelUndef);
4587           continue;
4588         }
4589         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4590         if (!CN)
4591           return false;
4592         APInt MaskElement = CN->getAPIntValue();
4593
4594         // We now have to decode the element which could be any integer size and
4595         // extract each byte of it.
4596         for (int j = 0; j < NumBytesPerElement; ++j) {
4597           // Note that this is x86 and so always little endian: the low byte is
4598           // the first byte of the mask.
4599           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4600           MaskElement = MaskElement.lshr(8);
4601         }
4602       }
4603       DecodePSHUFBMask(RawMask, Mask);
4604       break;
4605     }
4606
4607     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4608     if (!MaskLoad)
4609       return false;
4610
4611     SDValue Ptr = MaskLoad->getBasePtr();
4612     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4613         Ptr->getOpcode() == X86ISD::WrapperRIP)
4614       Ptr = Ptr->getOperand(0);
4615
4616     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4617     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4618       return false;
4619
4620     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4621       DecodePSHUFBMask(C, Mask);
4622       if (Mask.empty())
4623         return false;
4624       break;
4625     }
4626
4627     return false;
4628   }
4629   case X86ISD::VPERMI:
4630     ImmN = N->getOperand(N->getNumOperands()-1);
4631     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4632     IsUnary = true;
4633     break;
4634   case X86ISD::MOVSS:
4635   case X86ISD::MOVSD:
4636     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4637     break;
4638   case X86ISD::VPERM2X128:
4639     ImmN = N->getOperand(N->getNumOperands()-1);
4640     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4641     if (Mask.empty()) return false;
4642     // Mask only contains negative index if an element is zero.
4643     if (std::any_of(Mask.begin(), Mask.end(),
4644                     [](int M){ return M == SM_SentinelZero; }))
4645       return false;
4646     break;
4647   case X86ISD::MOVSLDUP:
4648     DecodeMOVSLDUPMask(VT, Mask);
4649     IsUnary = true;
4650     break;
4651   case X86ISD::MOVSHDUP:
4652     DecodeMOVSHDUPMask(VT, Mask);
4653     IsUnary = true;
4654     break;
4655   case X86ISD::MOVDDUP:
4656     DecodeMOVDDUPMask(VT, Mask);
4657     IsUnary = true;
4658     break;
4659   case X86ISD::MOVLHPD:
4660   case X86ISD::MOVLPD:
4661   case X86ISD::MOVLPS:
4662     // Not yet implemented
4663     return false;
4664   case X86ISD::VPERMV: {
4665     IsUnary = true;
4666     SDValue MaskNode = N->getOperand(0);
4667     while (MaskNode->getOpcode() == ISD::BITCAST)
4668       MaskNode = MaskNode->getOperand(0);
4669
4670     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4671     SmallVector<uint64_t, 32> RawMask;
4672     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4673       // If we have a build-vector, then things are easy.
4674       assert(MaskNode.getValueType().isInteger() &&
4675              MaskNode.getValueType().getVectorNumElements() ==
4676              VT.getVectorNumElements());
4677
4678       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4679         SDValue Op = MaskNode->getOperand(i);
4680         if (Op->getOpcode() == ISD::UNDEF)
4681           RawMask.push_back((uint64_t)SM_SentinelUndef);
4682         else if (isa<ConstantSDNode>(Op)) {
4683           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4684           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4685         } else
4686           return false;
4687       }
4688       DecodeVPERMVMask(RawMask, Mask);
4689       break;
4690     }
4691     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4692       unsigned NumEltsInMask = MaskNode->getNumOperands();
4693       MaskNode = MaskNode->getOperand(0);
4694       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4695       if (CN) {
4696         APInt MaskEltValue = CN->getAPIntValue();
4697         for (unsigned i = 0; i < NumEltsInMask; ++i)
4698           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4699         DecodeVPERMVMask(RawMask, Mask);
4700         break;
4701       }
4702       // It may be a scalar load
4703     }
4704
4705     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4706     if (!MaskLoad)
4707       return false;
4708
4709     SDValue Ptr = MaskLoad->getBasePtr();
4710     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4711         Ptr->getOpcode() == X86ISD::WrapperRIP)
4712       Ptr = Ptr->getOperand(0);
4713
4714     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4715     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4716       return false;
4717
4718     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4719     if (C) {
4720       DecodeVPERMVMask(C, VT, Mask);
4721       if (Mask.empty())
4722         return false;
4723       break;
4724     }
4725     return false;
4726   }
4727   case X86ISD::VPERMV3: {
4728     IsUnary = false;
4729     SDValue MaskNode = N->getOperand(1);
4730     while (MaskNode->getOpcode() == ISD::BITCAST)
4731       MaskNode = MaskNode->getOperand(1);
4732
4733     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4734       // If we have a build-vector, then things are easy.
4735       assert(MaskNode.getValueType().isInteger() &&
4736              MaskNode.getValueType().getVectorNumElements() ==
4737              VT.getVectorNumElements());
4738
4739       SmallVector<uint64_t, 32> RawMask;
4740       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4741
4742       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4743         SDValue Op = MaskNode->getOperand(i);
4744         if (Op->getOpcode() == ISD::UNDEF)
4745           RawMask.push_back((uint64_t)SM_SentinelUndef);
4746         else {
4747           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4748           if (!CN)
4749             return false;
4750           APInt MaskElement = CN->getAPIntValue();
4751           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4752         }
4753       }
4754       DecodeVPERMV3Mask(RawMask, Mask);
4755       break;
4756     }
4757
4758     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4759     if (!MaskLoad)
4760       return false;
4761
4762     SDValue Ptr = MaskLoad->getBasePtr();
4763     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4764         Ptr->getOpcode() == X86ISD::WrapperRIP)
4765       Ptr = Ptr->getOperand(0);
4766
4767     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4768     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4769       return false;
4770
4771     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4772     if (C) {
4773       DecodeVPERMV3Mask(C, VT, Mask);
4774       if (Mask.empty())
4775         return false;
4776       break;
4777     }
4778     return false;
4779   }
4780   default: llvm_unreachable("unknown target shuffle node");
4781   }
4782
4783   // If we have a fake unary shuffle, the shuffle mask is spread across two
4784   // inputs that are actually the same node. Re-map the mask to always point
4785   // into the first input.
4786   if (IsFakeUnary)
4787     for (int &M : Mask)
4788       if (M >= (int)Mask.size())
4789         M -= Mask.size();
4790
4791   return true;
4792 }
4793
4794 /// Returns the scalar element that will make up the ith
4795 /// element of the result of the vector shuffle.
4796 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4797                                    unsigned Depth) {
4798   if (Depth == 6)
4799     return SDValue();  // Limit search depth.
4800
4801   SDValue V = SDValue(N, 0);
4802   EVT VT = V.getValueType();
4803   unsigned Opcode = V.getOpcode();
4804
4805   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4806   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4807     int Elt = SV->getMaskElt(Index);
4808
4809     if (Elt < 0)
4810       return DAG.getUNDEF(VT.getVectorElementType());
4811
4812     unsigned NumElems = VT.getVectorNumElements();
4813     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4814                                          : SV->getOperand(1);
4815     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4816   }
4817
4818   // Recurse into target specific vector shuffles to find scalars.
4819   if (isTargetShuffle(Opcode)) {
4820     MVT ShufVT = V.getSimpleValueType();
4821     unsigned NumElems = ShufVT.getVectorNumElements();
4822     SmallVector<int, 16> ShuffleMask;
4823     bool IsUnary;
4824
4825     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4826       return SDValue();
4827
4828     int Elt = ShuffleMask[Index];
4829     if (Elt < 0)
4830       return DAG.getUNDEF(ShufVT.getVectorElementType());
4831
4832     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4833                                          : N->getOperand(1);
4834     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4835                                Depth+1);
4836   }
4837
4838   // Actual nodes that may contain scalar elements
4839   if (Opcode == ISD::BITCAST) {
4840     V = V.getOperand(0);
4841     EVT SrcVT = V.getValueType();
4842     unsigned NumElems = VT.getVectorNumElements();
4843
4844     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4845       return SDValue();
4846   }
4847
4848   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4849     return (Index == 0) ? V.getOperand(0)
4850                         : DAG.getUNDEF(VT.getVectorElementType());
4851
4852   if (V.getOpcode() == ISD::BUILD_VECTOR)
4853     return V.getOperand(Index);
4854
4855   return SDValue();
4856 }
4857
4858 /// Custom lower build_vector of v16i8.
4859 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4860                                        unsigned NumNonZero, unsigned NumZero,
4861                                        SelectionDAG &DAG,
4862                                        const X86Subtarget* Subtarget,
4863                                        const TargetLowering &TLI) {
4864   if (NumNonZero > 8)
4865     return SDValue();
4866
4867   SDLoc dl(Op);
4868   SDValue V;
4869   bool First = true;
4870
4871   // SSE4.1 - use PINSRB to insert each byte directly.
4872   if (Subtarget->hasSSE41()) {
4873     for (unsigned i = 0; i < 16; ++i) {
4874       bool isNonZero = (NonZeros & (1 << i)) != 0;
4875       if (isNonZero) {
4876         if (First) {
4877           if (NumZero)
4878             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4879           else
4880             V = DAG.getUNDEF(MVT::v16i8);
4881           First = false;
4882         }
4883         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4884                         MVT::v16i8, V, Op.getOperand(i),
4885                         DAG.getIntPtrConstant(i, dl));
4886       }
4887     }
4888
4889     return V;
4890   }
4891
4892   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4893   for (unsigned i = 0; i < 16; ++i) {
4894     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4895     if (ThisIsNonZero && First) {
4896       if (NumZero)
4897         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4898       else
4899         V = DAG.getUNDEF(MVT::v8i16);
4900       First = false;
4901     }
4902
4903     if ((i & 1) != 0) {
4904       SDValue ThisElt, LastElt;
4905       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4906       if (LastIsNonZero) {
4907         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4908                               MVT::i16, Op.getOperand(i-1));
4909       }
4910       if (ThisIsNonZero) {
4911         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4912         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4913                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4914         if (LastIsNonZero)
4915           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4916       } else
4917         ThisElt = LastElt;
4918
4919       if (ThisElt.getNode())
4920         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4921                         DAG.getIntPtrConstant(i/2, dl));
4922     }
4923   }
4924
4925   return DAG.getBitcast(MVT::v16i8, V);
4926 }
4927
4928 /// Custom lower build_vector of v8i16.
4929 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4930                                      unsigned NumNonZero, unsigned NumZero,
4931                                      SelectionDAG &DAG,
4932                                      const X86Subtarget* Subtarget,
4933                                      const TargetLowering &TLI) {
4934   if (NumNonZero > 4)
4935     return SDValue();
4936
4937   SDLoc dl(Op);
4938   SDValue V;
4939   bool First = true;
4940   for (unsigned i = 0; i < 8; ++i) {
4941     bool isNonZero = (NonZeros & (1 << i)) != 0;
4942     if (isNonZero) {
4943       if (First) {
4944         if (NumZero)
4945           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4946         else
4947           V = DAG.getUNDEF(MVT::v8i16);
4948         First = false;
4949       }
4950       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4951                       MVT::v8i16, V, Op.getOperand(i),
4952                       DAG.getIntPtrConstant(i, dl));
4953     }
4954   }
4955
4956   return V;
4957 }
4958
4959 /// Custom lower build_vector of v4i32 or v4f32.
4960 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4961                                      const X86Subtarget *Subtarget,
4962                                      const TargetLowering &TLI) {
4963   // Find all zeroable elements.
4964   std::bitset<4> Zeroable;
4965   for (int i=0; i < 4; ++i) {
4966     SDValue Elt = Op->getOperand(i);
4967     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4968   }
4969   assert(Zeroable.size() - Zeroable.count() > 1 &&
4970          "We expect at least two non-zero elements!");
4971
4972   // We only know how to deal with build_vector nodes where elements are either
4973   // zeroable or extract_vector_elt with constant index.
4974   SDValue FirstNonZero;
4975   unsigned FirstNonZeroIdx;
4976   for (unsigned i=0; i < 4; ++i) {
4977     if (Zeroable[i])
4978       continue;
4979     SDValue Elt = Op->getOperand(i);
4980     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4981         !isa<ConstantSDNode>(Elt.getOperand(1)))
4982       return SDValue();
4983     // Make sure that this node is extracting from a 128-bit vector.
4984     MVT VT = Elt.getOperand(0).getSimpleValueType();
4985     if (!VT.is128BitVector())
4986       return SDValue();
4987     if (!FirstNonZero.getNode()) {
4988       FirstNonZero = Elt;
4989       FirstNonZeroIdx = i;
4990     }
4991   }
4992
4993   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4994   SDValue V1 = FirstNonZero.getOperand(0);
4995   MVT VT = V1.getSimpleValueType();
4996
4997   // See if this build_vector can be lowered as a blend with zero.
4998   SDValue Elt;
4999   unsigned EltMaskIdx, EltIdx;
5000   int Mask[4];
5001   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5002     if (Zeroable[EltIdx]) {
5003       // The zero vector will be on the right hand side.
5004       Mask[EltIdx] = EltIdx+4;
5005       continue;
5006     }
5007
5008     Elt = Op->getOperand(EltIdx);
5009     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5010     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5011     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5012       break;
5013     Mask[EltIdx] = EltIdx;
5014   }
5015
5016   if (EltIdx == 4) {
5017     // Let the shuffle legalizer deal with blend operations.
5018     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5019     if (V1.getSimpleValueType() != VT)
5020       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5021     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5022   }
5023
5024   // See if we can lower this build_vector to a INSERTPS.
5025   if (!Subtarget->hasSSE41())
5026     return SDValue();
5027
5028   SDValue V2 = Elt.getOperand(0);
5029   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5030     V1 = SDValue();
5031
5032   bool CanFold = true;
5033   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5034     if (Zeroable[i])
5035       continue;
5036
5037     SDValue Current = Op->getOperand(i);
5038     SDValue SrcVector = Current->getOperand(0);
5039     if (!V1.getNode())
5040       V1 = SrcVector;
5041     CanFold = SrcVector == V1 &&
5042       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5043   }
5044
5045   if (!CanFold)
5046     return SDValue();
5047
5048   assert(V1.getNode() && "Expected at least two non-zero elements!");
5049   if (V1.getSimpleValueType() != MVT::v4f32)
5050     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5051   if (V2.getSimpleValueType() != MVT::v4f32)
5052     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5053
5054   // Ok, we can emit an INSERTPS instruction.
5055   unsigned ZMask = Zeroable.to_ulong();
5056
5057   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5058   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5059   SDLoc DL(Op);
5060   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5061                                DAG.getIntPtrConstant(InsertPSMask, DL));
5062   return DAG.getBitcast(VT, Result);
5063 }
5064
5065 /// Return a vector logical shift node.
5066 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5067                          unsigned NumBits, SelectionDAG &DAG,
5068                          const TargetLowering &TLI, SDLoc dl) {
5069   assert(VT.is128BitVector() && "Unknown type for VShift");
5070   MVT ShVT = MVT::v2i64;
5071   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5072   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5073   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5074   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5075   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5076   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5077 }
5078
5079 static SDValue
5080 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5081
5082   // Check if the scalar load can be widened into a vector load. And if
5083   // the address is "base + cst" see if the cst can be "absorbed" into
5084   // the shuffle mask.
5085   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5086     SDValue Ptr = LD->getBasePtr();
5087     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5088       return SDValue();
5089     EVT PVT = LD->getValueType(0);
5090     if (PVT != MVT::i32 && PVT != MVT::f32)
5091       return SDValue();
5092
5093     int FI = -1;
5094     int64_t Offset = 0;
5095     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5096       FI = FINode->getIndex();
5097       Offset = 0;
5098     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5099                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5100       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5101       Offset = Ptr.getConstantOperandVal(1);
5102       Ptr = Ptr.getOperand(0);
5103     } else {
5104       return SDValue();
5105     }
5106
5107     // FIXME: 256-bit vector instructions don't require a strict alignment,
5108     // improve this code to support it better.
5109     unsigned RequiredAlign = VT.getSizeInBits()/8;
5110     SDValue Chain = LD->getChain();
5111     // Make sure the stack object alignment is at least 16 or 32.
5112     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5113     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5114       if (MFI->isFixedObjectIndex(FI)) {
5115         // Can't change the alignment. FIXME: It's possible to compute
5116         // the exact stack offset and reference FI + adjust offset instead.
5117         // If someone *really* cares about this. That's the way to implement it.
5118         return SDValue();
5119       } else {
5120         MFI->setObjectAlignment(FI, RequiredAlign);
5121       }
5122     }
5123
5124     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5125     // Ptr + (Offset & ~15).
5126     if (Offset < 0)
5127       return SDValue();
5128     if ((Offset % RequiredAlign) & 3)
5129       return SDValue();
5130     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5131     if (StartOffset) {
5132       SDLoc DL(Ptr);
5133       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5134                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5135     }
5136
5137     int EltNo = (Offset - StartOffset) >> 2;
5138     unsigned NumElems = VT.getVectorNumElements();
5139
5140     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5141     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5142                              LD->getPointerInfo().getWithOffset(StartOffset),
5143                              false, false, false, 0);
5144
5145     SmallVector<int, 8> Mask(NumElems, EltNo);
5146
5147     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5148   }
5149
5150   return SDValue();
5151 }
5152
5153 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5154 /// elements can be replaced by a single large load which has the same value as
5155 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5156 ///
5157 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5158 ///
5159 /// FIXME: we'd also like to handle the case where the last elements are zero
5160 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5161 /// There's even a handy isZeroNode for that purpose.
5162 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5163                                         SDLoc &DL, SelectionDAG &DAG,
5164                                         bool isAfterLegalize) {
5165   unsigned NumElems = Elts.size();
5166
5167   LoadSDNode *LDBase = nullptr;
5168   unsigned LastLoadedElt = -1U;
5169
5170   // For each element in the initializer, see if we've found a load or an undef.
5171   // If we don't find an initial load element, or later load elements are
5172   // non-consecutive, bail out.
5173   for (unsigned i = 0; i < NumElems; ++i) {
5174     SDValue Elt = Elts[i];
5175     // Look through a bitcast.
5176     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5177       Elt = Elt.getOperand(0);
5178     if (!Elt.getNode() ||
5179         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5180       return SDValue();
5181     if (!LDBase) {
5182       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5183         return SDValue();
5184       LDBase = cast<LoadSDNode>(Elt.getNode());
5185       LastLoadedElt = i;
5186       continue;
5187     }
5188     if (Elt.getOpcode() == ISD::UNDEF)
5189       continue;
5190
5191     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5192     EVT LdVT = Elt.getValueType();
5193     // Each loaded element must be the correct fractional portion of the
5194     // requested vector load.
5195     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5196       return SDValue();
5197     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5198       return SDValue();
5199     LastLoadedElt = i;
5200   }
5201
5202   // If we have found an entire vector of loads and undefs, then return a large
5203   // load of the entire vector width starting at the base pointer.  If we found
5204   // consecutive loads for the low half, generate a vzext_load node.
5205   if (LastLoadedElt == NumElems - 1) {
5206     assert(LDBase && "Did not find base load for merging consecutive loads");
5207     EVT EltVT = LDBase->getValueType(0);
5208     // Ensure that the input vector size for the merged loads matches the
5209     // cumulative size of the input elements.
5210     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5211       return SDValue();
5212
5213     if (isAfterLegalize &&
5214         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5215       return SDValue();
5216
5217     SDValue NewLd = SDValue();
5218
5219     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5220                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5221                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5222                         LDBase->getAlignment());
5223
5224     if (LDBase->hasAnyUseOfValue(1)) {
5225       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5226                                      SDValue(LDBase, 1),
5227                                      SDValue(NewLd.getNode(), 1));
5228       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5229       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5230                              SDValue(NewLd.getNode(), 1));
5231     }
5232
5233     return NewLd;
5234   }
5235
5236   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5237   //of a v4i32 / v4f32. It's probably worth generalizing.
5238   EVT EltVT = VT.getVectorElementType();
5239   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5240       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5241     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5242     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5243     SDValue ResNode =
5244         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5245                                 LDBase->getPointerInfo(),
5246                                 LDBase->getAlignment(),
5247                                 false/*isVolatile*/, true/*ReadMem*/,
5248                                 false/*WriteMem*/);
5249
5250     // Make sure the newly-created LOAD is in the same position as LDBase in
5251     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5252     // update uses of LDBase's output chain to use the TokenFactor.
5253     if (LDBase->hasAnyUseOfValue(1)) {
5254       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5255                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5256       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5257       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5258                              SDValue(ResNode.getNode(), 1));
5259     }
5260
5261     return DAG.getBitcast(VT, ResNode);
5262   }
5263   return SDValue();
5264 }
5265
5266 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5267 /// to generate a splat value for the following cases:
5268 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5269 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5270 /// a scalar load, or a constant.
5271 /// The VBROADCAST node is returned when a pattern is found,
5272 /// or SDValue() otherwise.
5273 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5274                                     SelectionDAG &DAG) {
5275   // VBROADCAST requires AVX.
5276   // TODO: Splats could be generated for non-AVX CPUs using SSE
5277   // instructions, but there's less potential gain for only 128-bit vectors.
5278   if (!Subtarget->hasAVX())
5279     return SDValue();
5280
5281   MVT VT = Op.getSimpleValueType();
5282   SDLoc dl(Op);
5283
5284   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5285          "Unsupported vector type for broadcast.");
5286
5287   SDValue Ld;
5288   bool ConstSplatVal;
5289
5290   switch (Op.getOpcode()) {
5291     default:
5292       // Unknown pattern found.
5293       return SDValue();
5294
5295     case ISD::BUILD_VECTOR: {
5296       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5297       BitVector UndefElements;
5298       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5299
5300       // We need a splat of a single value to use broadcast, and it doesn't
5301       // make any sense if the value is only in one element of the vector.
5302       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5303         return SDValue();
5304
5305       Ld = Splat;
5306       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5307                        Ld.getOpcode() == ISD::ConstantFP);
5308
5309       // Make sure that all of the users of a non-constant load are from the
5310       // BUILD_VECTOR node.
5311       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5312         return SDValue();
5313       break;
5314     }
5315
5316     case ISD::VECTOR_SHUFFLE: {
5317       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5318
5319       // Shuffles must have a splat mask where the first element is
5320       // broadcasted.
5321       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5322         return SDValue();
5323
5324       SDValue Sc = Op.getOperand(0);
5325       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5326           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5327
5328         if (!Subtarget->hasInt256())
5329           return SDValue();
5330
5331         // Use the register form of the broadcast instruction available on AVX2.
5332         if (VT.getSizeInBits() >= 256)
5333           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5334         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5335       }
5336
5337       Ld = Sc.getOperand(0);
5338       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5339                        Ld.getOpcode() == ISD::ConstantFP);
5340
5341       // The scalar_to_vector node and the suspected
5342       // load node must have exactly one user.
5343       // Constants may have multiple users.
5344
5345       // AVX-512 has register version of the broadcast
5346       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5347         Ld.getValueType().getSizeInBits() >= 32;
5348       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5349           !hasRegVer))
5350         return SDValue();
5351       break;
5352     }
5353   }
5354
5355   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5356   bool IsGE256 = (VT.getSizeInBits() >= 256);
5357
5358   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5359   // instruction to save 8 or more bytes of constant pool data.
5360   // TODO: If multiple splats are generated to load the same constant,
5361   // it may be detrimental to overall size. There needs to be a way to detect
5362   // that condition to know if this is truly a size win.
5363   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5364
5365   // Handle broadcasting a single constant scalar from the constant pool
5366   // into a vector.
5367   // On Sandybridge (no AVX2), it is still better to load a constant vector
5368   // from the constant pool and not to broadcast it from a scalar.
5369   // But override that restriction when optimizing for size.
5370   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5371   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5372     EVT CVT = Ld.getValueType();
5373     assert(!CVT.isVector() && "Must not broadcast a vector type");
5374
5375     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5376     // For size optimization, also splat v2f64 and v2i64, and for size opt
5377     // with AVX2, also splat i8 and i16.
5378     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5379     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5380         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5381       const Constant *C = nullptr;
5382       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5383         C = CI->getConstantIntValue();
5384       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5385         C = CF->getConstantFPValue();
5386
5387       assert(C && "Invalid constant type");
5388
5389       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5390       SDValue CP =
5391           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5392       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5393       Ld = DAG.getLoad(
5394           CVT, dl, DAG.getEntryNode(), CP,
5395           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5396           false, false, Alignment);
5397
5398       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5399     }
5400   }
5401
5402   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5403
5404   // Handle AVX2 in-register broadcasts.
5405   if (!IsLoad && Subtarget->hasInt256() &&
5406       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5407     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5408
5409   // The scalar source must be a normal load.
5410   if (!IsLoad)
5411     return SDValue();
5412
5413   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5414       (Subtarget->hasVLX() && ScalarSize == 64))
5415     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5416
5417   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5418   // double since there is no vbroadcastsd xmm
5419   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5420     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5421       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5422   }
5423
5424   // Unsupported broadcast.
5425   return SDValue();
5426 }
5427
5428 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5429 /// underlying vector and index.
5430 ///
5431 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5432 /// index.
5433 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5434                                          SDValue ExtIdx) {
5435   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5436   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5437     return Idx;
5438
5439   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5440   // lowered this:
5441   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5442   // to:
5443   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5444   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5445   //                           undef)
5446   //                       Constant<0>)
5447   // In this case the vector is the extract_subvector expression and the index
5448   // is 2, as specified by the shuffle.
5449   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5450   SDValue ShuffleVec = SVOp->getOperand(0);
5451   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5452   assert(ShuffleVecVT.getVectorElementType() ==
5453          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5454
5455   int ShuffleIdx = SVOp->getMaskElt(Idx);
5456   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5457     ExtractedFromVec = ShuffleVec;
5458     return ShuffleIdx;
5459   }
5460   return Idx;
5461 }
5462
5463 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5464   MVT VT = Op.getSimpleValueType();
5465
5466   // Skip if insert_vec_elt is not supported.
5467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5468   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5469     return SDValue();
5470
5471   SDLoc DL(Op);
5472   unsigned NumElems = Op.getNumOperands();
5473
5474   SDValue VecIn1;
5475   SDValue VecIn2;
5476   SmallVector<unsigned, 4> InsertIndices;
5477   SmallVector<int, 8> Mask(NumElems, -1);
5478
5479   for (unsigned i = 0; i != NumElems; ++i) {
5480     unsigned Opc = Op.getOperand(i).getOpcode();
5481
5482     if (Opc == ISD::UNDEF)
5483       continue;
5484
5485     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5486       // Quit if more than 1 elements need inserting.
5487       if (InsertIndices.size() > 1)
5488         return SDValue();
5489
5490       InsertIndices.push_back(i);
5491       continue;
5492     }
5493
5494     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5495     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5496     // Quit if non-constant index.
5497     if (!isa<ConstantSDNode>(ExtIdx))
5498       return SDValue();
5499     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5500
5501     // Quit if extracted from vector of different type.
5502     if (ExtractedFromVec.getValueType() != VT)
5503       return SDValue();
5504
5505     if (!VecIn1.getNode())
5506       VecIn1 = ExtractedFromVec;
5507     else if (VecIn1 != ExtractedFromVec) {
5508       if (!VecIn2.getNode())
5509         VecIn2 = ExtractedFromVec;
5510       else if (VecIn2 != ExtractedFromVec)
5511         // Quit if more than 2 vectors to shuffle
5512         return SDValue();
5513     }
5514
5515     if (ExtractedFromVec == VecIn1)
5516       Mask[i] = Idx;
5517     else if (ExtractedFromVec == VecIn2)
5518       Mask[i] = Idx + NumElems;
5519   }
5520
5521   if (!VecIn1.getNode())
5522     return SDValue();
5523
5524   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5525   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5526   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5527     unsigned Idx = InsertIndices[i];
5528     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5529                      DAG.getIntPtrConstant(Idx, DL));
5530   }
5531
5532   return NV;
5533 }
5534
5535 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5536   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5537          Op.getScalarValueSizeInBits() == 1 &&
5538          "Can not convert non-constant vector");
5539   uint64_t Immediate = 0;
5540   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5541     SDValue In = Op.getOperand(idx);
5542     if (In.getOpcode() != ISD::UNDEF)
5543       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5544   }
5545   SDLoc dl(Op);
5546   MVT VT =
5547    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5548   return DAG.getConstant(Immediate, dl, VT);
5549 }
5550 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5551 SDValue
5552 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5553
5554   MVT VT = Op.getSimpleValueType();
5555   assert((VT.getVectorElementType() == MVT::i1) &&
5556          "Unexpected type in LowerBUILD_VECTORvXi1!");
5557
5558   SDLoc dl(Op);
5559   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5560     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5561     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5562     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5563   }
5564
5565   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5566     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5567     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5568     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5569   }
5570
5571   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5572     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5573     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5574       return DAG.getBitcast(VT, Imm);
5575     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5576     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5577                         DAG.getIntPtrConstant(0, dl));
5578   }
5579
5580   // Vector has one or more non-const elements
5581   uint64_t Immediate = 0;
5582   SmallVector<unsigned, 16> NonConstIdx;
5583   bool IsSplat = true;
5584   bool HasConstElts = false;
5585   int SplatIdx = -1;
5586   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5587     SDValue In = Op.getOperand(idx);
5588     if (In.getOpcode() == ISD::UNDEF)
5589       continue;
5590     if (!isa<ConstantSDNode>(In))
5591       NonConstIdx.push_back(idx);
5592     else {
5593       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5594       HasConstElts = true;
5595     }
5596     if (SplatIdx == -1)
5597       SplatIdx = idx;
5598     else if (In != Op.getOperand(SplatIdx))
5599       IsSplat = false;
5600   }
5601
5602   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5603   if (IsSplat)
5604     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5605                        DAG.getConstant(1, dl, VT),
5606                        DAG.getConstant(0, dl, VT));
5607
5608   // insert elements one by one
5609   SDValue DstVec;
5610   SDValue Imm;
5611   if (Immediate) {
5612     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5613     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5614   }
5615   else if (HasConstElts)
5616     Imm = DAG.getConstant(0, dl, VT);
5617   else
5618     Imm = DAG.getUNDEF(VT);
5619   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5620     DstVec = DAG.getBitcast(VT, Imm);
5621   else {
5622     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5623     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5624                          DAG.getIntPtrConstant(0, dl));
5625   }
5626
5627   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5628     unsigned InsertIdx = NonConstIdx[i];
5629     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5630                          Op.getOperand(InsertIdx),
5631                          DAG.getIntPtrConstant(InsertIdx, dl));
5632   }
5633   return DstVec;
5634 }
5635
5636 /// \brief Return true if \p N implements a horizontal binop and return the
5637 /// operands for the horizontal binop into V0 and V1.
5638 ///
5639 /// This is a helper function of LowerToHorizontalOp().
5640 /// This function checks that the build_vector \p N in input implements a
5641 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5642 /// operation to match.
5643 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5644 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5645 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5646 /// arithmetic sub.
5647 ///
5648 /// This function only analyzes elements of \p N whose indices are
5649 /// in range [BaseIdx, LastIdx).
5650 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5651                               SelectionDAG &DAG,
5652                               unsigned BaseIdx, unsigned LastIdx,
5653                               SDValue &V0, SDValue &V1) {
5654   EVT VT = N->getValueType(0);
5655
5656   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5657   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5658          "Invalid Vector in input!");
5659
5660   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5661   bool CanFold = true;
5662   unsigned ExpectedVExtractIdx = BaseIdx;
5663   unsigned NumElts = LastIdx - BaseIdx;
5664   V0 = DAG.getUNDEF(VT);
5665   V1 = DAG.getUNDEF(VT);
5666
5667   // Check if N implements a horizontal binop.
5668   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5669     SDValue Op = N->getOperand(i + BaseIdx);
5670
5671     // Skip UNDEFs.
5672     if (Op->getOpcode() == ISD::UNDEF) {
5673       // Update the expected vector extract index.
5674       if (i * 2 == NumElts)
5675         ExpectedVExtractIdx = BaseIdx;
5676       ExpectedVExtractIdx += 2;
5677       continue;
5678     }
5679
5680     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5681
5682     if (!CanFold)
5683       break;
5684
5685     SDValue Op0 = Op.getOperand(0);
5686     SDValue Op1 = Op.getOperand(1);
5687
5688     // Try to match the following pattern:
5689     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5690     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5691         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5692         Op0.getOperand(0) == Op1.getOperand(0) &&
5693         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5694         isa<ConstantSDNode>(Op1.getOperand(1)));
5695     if (!CanFold)
5696       break;
5697
5698     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5699     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5700
5701     if (i * 2 < NumElts) {
5702       if (V0.getOpcode() == ISD::UNDEF) {
5703         V0 = Op0.getOperand(0);
5704         if (V0.getValueType() != VT)
5705           return false;
5706       }
5707     } else {
5708       if (V1.getOpcode() == ISD::UNDEF) {
5709         V1 = Op0.getOperand(0);
5710         if (V1.getValueType() != VT)
5711           return false;
5712       }
5713       if (i * 2 == NumElts)
5714         ExpectedVExtractIdx = BaseIdx;
5715     }
5716
5717     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5718     if (I0 == ExpectedVExtractIdx)
5719       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5720     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5721       // Try to match the following dag sequence:
5722       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5723       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5724     } else
5725       CanFold = false;
5726
5727     ExpectedVExtractIdx += 2;
5728   }
5729
5730   return CanFold;
5731 }
5732
5733 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5734 /// a concat_vector.
5735 ///
5736 /// This is a helper function of LowerToHorizontalOp().
5737 /// This function expects two 256-bit vectors called V0 and V1.
5738 /// At first, each vector is split into two separate 128-bit vectors.
5739 /// Then, the resulting 128-bit vectors are used to implement two
5740 /// horizontal binary operations.
5741 ///
5742 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5743 ///
5744 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5745 /// the two new horizontal binop.
5746 /// When Mode is set, the first horizontal binop dag node would take as input
5747 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5748 /// horizontal binop dag node would take as input the lower 128-bit of V1
5749 /// and the upper 128-bit of V1.
5750 ///   Example:
5751 ///     HADD V0_LO, V0_HI
5752 ///     HADD V1_LO, V1_HI
5753 ///
5754 /// Otherwise, the first horizontal binop dag node takes as input the lower
5755 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5756 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5757 ///   Example:
5758 ///     HADD V0_LO, V1_LO
5759 ///     HADD V0_HI, V1_HI
5760 ///
5761 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5762 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5763 /// the upper 128-bits of the result.
5764 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5765                                      SDLoc DL, SelectionDAG &DAG,
5766                                      unsigned X86Opcode, bool Mode,
5767                                      bool isUndefLO, bool isUndefHI) {
5768   EVT VT = V0.getValueType();
5769   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5770          "Invalid nodes in input!");
5771
5772   unsigned NumElts = VT.getVectorNumElements();
5773   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5774   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5775   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5776   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5777   EVT NewVT = V0_LO.getValueType();
5778
5779   SDValue LO = DAG.getUNDEF(NewVT);
5780   SDValue HI = DAG.getUNDEF(NewVT);
5781
5782   if (Mode) {
5783     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5784     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5785       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5786     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5787       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5788   } else {
5789     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5790     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5791                        V1_LO->getOpcode() != ISD::UNDEF))
5792       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5793
5794     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5795                        V1_HI->getOpcode() != ISD::UNDEF))
5796       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5797   }
5798
5799   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5800 }
5801
5802 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5803 /// node.
5804 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5805                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5806   EVT VT = BV->getValueType(0);
5807   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5808       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5809     return SDValue();
5810
5811   SDLoc DL(BV);
5812   unsigned NumElts = VT.getVectorNumElements();
5813   SDValue InVec0 = DAG.getUNDEF(VT);
5814   SDValue InVec1 = DAG.getUNDEF(VT);
5815
5816   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5817           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5818
5819   // Odd-numbered elements in the input build vector are obtained from
5820   // adding two integer/float elements.
5821   // Even-numbered elements in the input build vector are obtained from
5822   // subtracting two integer/float elements.
5823   unsigned ExpectedOpcode = ISD::FSUB;
5824   unsigned NextExpectedOpcode = ISD::FADD;
5825   bool AddFound = false;
5826   bool SubFound = false;
5827
5828   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5829     SDValue Op = BV->getOperand(i);
5830
5831     // Skip 'undef' values.
5832     unsigned Opcode = Op.getOpcode();
5833     if (Opcode == ISD::UNDEF) {
5834       std::swap(ExpectedOpcode, NextExpectedOpcode);
5835       continue;
5836     }
5837
5838     // Early exit if we found an unexpected opcode.
5839     if (Opcode != ExpectedOpcode)
5840       return SDValue();
5841
5842     SDValue Op0 = Op.getOperand(0);
5843     SDValue Op1 = Op.getOperand(1);
5844
5845     // Try to match the following pattern:
5846     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5847     // Early exit if we cannot match that sequence.
5848     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5849         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5850         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5851         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5852         Op0.getOperand(1) != Op1.getOperand(1))
5853       return SDValue();
5854
5855     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5856     if (I0 != i)
5857       return SDValue();
5858
5859     // We found a valid add/sub node. Update the information accordingly.
5860     if (i & 1)
5861       AddFound = true;
5862     else
5863       SubFound = true;
5864
5865     // Update InVec0 and InVec1.
5866     if (InVec0.getOpcode() == ISD::UNDEF) {
5867       InVec0 = Op0.getOperand(0);
5868       if (InVec0.getValueType() != VT)
5869         return SDValue();
5870     }
5871     if (InVec1.getOpcode() == ISD::UNDEF) {
5872       InVec1 = Op1.getOperand(0);
5873       if (InVec1.getValueType() != VT)
5874         return SDValue();
5875     }
5876
5877     // Make sure that operands in input to each add/sub node always
5878     // come from a same pair of vectors.
5879     if (InVec0 != Op0.getOperand(0)) {
5880       if (ExpectedOpcode == ISD::FSUB)
5881         return SDValue();
5882
5883       // FADD is commutable. Try to commute the operands
5884       // and then test again.
5885       std::swap(Op0, Op1);
5886       if (InVec0 != Op0.getOperand(0))
5887         return SDValue();
5888     }
5889
5890     if (InVec1 != Op1.getOperand(0))
5891       return SDValue();
5892
5893     // Update the pair of expected opcodes.
5894     std::swap(ExpectedOpcode, NextExpectedOpcode);
5895   }
5896
5897   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5898   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5899       InVec1.getOpcode() != ISD::UNDEF)
5900     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5901
5902   return SDValue();
5903 }
5904
5905 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5906 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5907                                    const X86Subtarget *Subtarget,
5908                                    SelectionDAG &DAG) {
5909   EVT VT = BV->getValueType(0);
5910   unsigned NumElts = VT.getVectorNumElements();
5911   unsigned NumUndefsLO = 0;
5912   unsigned NumUndefsHI = 0;
5913   unsigned Half = NumElts/2;
5914
5915   // Count the number of UNDEF operands in the build_vector in input.
5916   for (unsigned i = 0, e = Half; i != e; ++i)
5917     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5918       NumUndefsLO++;
5919
5920   for (unsigned i = Half, e = NumElts; i != e; ++i)
5921     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5922       NumUndefsHI++;
5923
5924   // Early exit if this is either a build_vector of all UNDEFs or all the
5925   // operands but one are UNDEF.
5926   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5927     return SDValue();
5928
5929   SDLoc DL(BV);
5930   SDValue InVec0, InVec1;
5931   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5932     // Try to match an SSE3 float HADD/HSUB.
5933     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5934       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5935
5936     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5937       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5938   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5939     // Try to match an SSSE3 integer HADD/HSUB.
5940     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5941       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5942
5943     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5944       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5945   }
5946
5947   if (!Subtarget->hasAVX())
5948     return SDValue();
5949
5950   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5951     // Try to match an AVX horizontal add/sub of packed single/double
5952     // precision floating point values from 256-bit vectors.
5953     SDValue InVec2, InVec3;
5954     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5955         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5956         ((InVec0.getOpcode() == ISD::UNDEF ||
5957           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5958         ((InVec1.getOpcode() == ISD::UNDEF ||
5959           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5960       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5961
5962     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5963         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5964         ((InVec0.getOpcode() == ISD::UNDEF ||
5965           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5966         ((InVec1.getOpcode() == ISD::UNDEF ||
5967           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5968       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5969   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5970     // Try to match an AVX2 horizontal add/sub of signed integers.
5971     SDValue InVec2, InVec3;
5972     unsigned X86Opcode;
5973     bool CanFold = true;
5974
5975     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5976         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5977         ((InVec0.getOpcode() == ISD::UNDEF ||
5978           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5979         ((InVec1.getOpcode() == ISD::UNDEF ||
5980           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5981       X86Opcode = X86ISD::HADD;
5982     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5983         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5984         ((InVec0.getOpcode() == ISD::UNDEF ||
5985           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5986         ((InVec1.getOpcode() == ISD::UNDEF ||
5987           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5988       X86Opcode = X86ISD::HSUB;
5989     else
5990       CanFold = false;
5991
5992     if (CanFold) {
5993       // Fold this build_vector into a single horizontal add/sub.
5994       // Do this only if the target has AVX2.
5995       if (Subtarget->hasAVX2())
5996         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5997
5998       // Do not try to expand this build_vector into a pair of horizontal
5999       // add/sub if we can emit a pair of scalar add/sub.
6000       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6001         return SDValue();
6002
6003       // Convert this build_vector into a pair of horizontal binop followed by
6004       // a concat vector.
6005       bool isUndefLO = NumUndefsLO == Half;
6006       bool isUndefHI = NumUndefsHI == Half;
6007       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6008                                    isUndefLO, isUndefHI);
6009     }
6010   }
6011
6012   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6013        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6014     unsigned X86Opcode;
6015     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6016       X86Opcode = X86ISD::HADD;
6017     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6018       X86Opcode = X86ISD::HSUB;
6019     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6020       X86Opcode = X86ISD::FHADD;
6021     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6022       X86Opcode = X86ISD::FHSUB;
6023     else
6024       return SDValue();
6025
6026     // Don't try to expand this build_vector into a pair of horizontal add/sub
6027     // if we can simply emit a pair of scalar add/sub.
6028     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6029       return SDValue();
6030
6031     // Convert this build_vector into two horizontal add/sub followed by
6032     // a concat vector.
6033     bool isUndefLO = NumUndefsLO == Half;
6034     bool isUndefHI = NumUndefsHI == Half;
6035     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6036                                  isUndefLO, isUndefHI);
6037   }
6038
6039   return SDValue();
6040 }
6041
6042 SDValue
6043 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6044   SDLoc dl(Op);
6045
6046   MVT VT = Op.getSimpleValueType();
6047   MVT ExtVT = VT.getVectorElementType();
6048   unsigned NumElems = Op.getNumOperands();
6049
6050   // Generate vectors for predicate vectors.
6051   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6052     return LowerBUILD_VECTORvXi1(Op, DAG);
6053
6054   // Vectors containing all zeros can be matched by pxor and xorps later
6055   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6056     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6057     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6058     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6059       return Op;
6060
6061     return getZeroVector(VT, Subtarget, DAG, dl);
6062   }
6063
6064   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6065   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6066   // vpcmpeqd on 256-bit vectors.
6067   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6068     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6069       return Op;
6070
6071     if (!VT.is512BitVector())
6072       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6073   }
6074
6075   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6076   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6077     return AddSub;
6078   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6079     return HorizontalOp;
6080   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6081     return Broadcast;
6082
6083   unsigned EVTBits = ExtVT.getSizeInBits();
6084
6085   unsigned NumZero  = 0;
6086   unsigned NumNonZero = 0;
6087   unsigned NonZeros = 0;
6088   bool IsAllConstants = true;
6089   SmallSet<SDValue, 8> Values;
6090   for (unsigned i = 0; i < NumElems; ++i) {
6091     SDValue Elt = Op.getOperand(i);
6092     if (Elt.getOpcode() == ISD::UNDEF)
6093       continue;
6094     Values.insert(Elt);
6095     if (Elt.getOpcode() != ISD::Constant &&
6096         Elt.getOpcode() != ISD::ConstantFP)
6097       IsAllConstants = false;
6098     if (X86::isZeroNode(Elt))
6099       NumZero++;
6100     else {
6101       NonZeros |= (1 << i);
6102       NumNonZero++;
6103     }
6104   }
6105
6106   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6107   if (NumNonZero == 0)
6108     return DAG.getUNDEF(VT);
6109
6110   // Special case for single non-zero, non-undef, element.
6111   if (NumNonZero == 1) {
6112     unsigned Idx = countTrailingZeros(NonZeros);
6113     SDValue Item = Op.getOperand(Idx);
6114
6115     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6116     // the value are obviously zero, truncate the value to i32 and do the
6117     // insertion that way.  Only do this if the value is non-constant or if the
6118     // value is a constant being inserted into element 0.  It is cheaper to do
6119     // a constant pool load than it is to do a movd + shuffle.
6120     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6121         (!IsAllConstants || Idx == 0)) {
6122       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6123         // Handle SSE only.
6124         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6125         EVT VecVT = MVT::v4i32;
6126
6127         // Truncate the value (which may itself be a constant) to i32, and
6128         // convert it to a vector with movd (S2V+shuffle to zero extend).
6129         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6130         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6131         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6132                                       Item, Idx * 2, true, Subtarget, DAG));
6133       }
6134     }
6135
6136     // If we have a constant or non-constant insertion into the low element of
6137     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6138     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6139     // depending on what the source datatype is.
6140     if (Idx == 0) {
6141       if (NumZero == 0)
6142         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6143
6144       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6145           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6146         if (VT.is512BitVector()) {
6147           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6148           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6149                              Item, DAG.getIntPtrConstant(0, dl));
6150         }
6151         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6152                "Expected an SSE value type!");
6153         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6154         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6155         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6156       }
6157
6158       // We can't directly insert an i8 or i16 into a vector, so zero extend
6159       // it to i32 first.
6160       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6161         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6162         if (VT.is256BitVector()) {
6163           if (Subtarget->hasAVX()) {
6164             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6165             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6166           } else {
6167             // Without AVX, we need to extend to a 128-bit vector and then
6168             // insert into the 256-bit vector.
6169             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6170             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6171             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6172           }
6173         } else {
6174           assert(VT.is128BitVector() && "Expected an SSE value type!");
6175           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6176           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6177         }
6178         return DAG.getBitcast(VT, Item);
6179       }
6180     }
6181
6182     // Is it a vector logical left shift?
6183     if (NumElems == 2 && Idx == 1 &&
6184         X86::isZeroNode(Op.getOperand(0)) &&
6185         !X86::isZeroNode(Op.getOperand(1))) {
6186       unsigned NumBits = VT.getSizeInBits();
6187       return getVShift(true, VT,
6188                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6189                                    VT, Op.getOperand(1)),
6190                        NumBits/2, DAG, *this, dl);
6191     }
6192
6193     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6194       return SDValue();
6195
6196     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6197     // is a non-constant being inserted into an element other than the low one,
6198     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6199     // movd/movss) to move this into the low element, then shuffle it into
6200     // place.
6201     if (EVTBits == 32) {
6202       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6203       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6204     }
6205   }
6206
6207   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6208   if (Values.size() == 1) {
6209     if (EVTBits == 32) {
6210       // Instead of a shuffle like this:
6211       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6212       // Check if it's possible to issue this instead.
6213       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6214       unsigned Idx = countTrailingZeros(NonZeros);
6215       SDValue Item = Op.getOperand(Idx);
6216       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6217         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6218     }
6219     return SDValue();
6220   }
6221
6222   // A vector full of immediates; various special cases are already
6223   // handled, so this is best done with a single constant-pool load.
6224   if (IsAllConstants)
6225     return SDValue();
6226
6227   // For AVX-length vectors, see if we can use a vector load to get all of the
6228   // elements, otherwise build the individual 128-bit pieces and use
6229   // shuffles to put them in place.
6230   if (VT.is256BitVector() || VT.is512BitVector()) {
6231     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6232
6233     // Check for a build vector of consecutive loads.
6234     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6235       return LD;
6236
6237     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6238
6239     // Build both the lower and upper subvector.
6240     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6241                                 makeArrayRef(&V[0], NumElems/2));
6242     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6243                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6244
6245     // Recreate the wider vector with the lower and upper part.
6246     if (VT.is256BitVector())
6247       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6248     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6249   }
6250
6251   // Let legalizer expand 2-wide build_vectors.
6252   if (EVTBits == 64) {
6253     if (NumNonZero == 1) {
6254       // One half is zero or undef.
6255       unsigned Idx = countTrailingZeros(NonZeros);
6256       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6257                                  Op.getOperand(Idx));
6258       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6259     }
6260     return SDValue();
6261   }
6262
6263   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6264   if (EVTBits == 8 && NumElems == 16)
6265     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6266                                         Subtarget, *this))
6267       return V;
6268
6269   if (EVTBits == 16 && NumElems == 8)
6270     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6271                                       Subtarget, *this))
6272       return V;
6273
6274   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6275   if (EVTBits == 32 && NumElems == 4)
6276     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6277       return V;
6278
6279   // If element VT is == 32 bits, turn it into a number of shuffles.
6280   SmallVector<SDValue, 8> V(NumElems);
6281   if (NumElems == 4 && NumZero > 0) {
6282     for (unsigned i = 0; i < 4; ++i) {
6283       bool isZero = !(NonZeros & (1 << i));
6284       if (isZero)
6285         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6286       else
6287         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6288     }
6289
6290     for (unsigned i = 0; i < 2; ++i) {
6291       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6292         default: break;
6293         case 0:
6294           V[i] = V[i*2];  // Must be a zero vector.
6295           break;
6296         case 1:
6297           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6298           break;
6299         case 2:
6300           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6301           break;
6302         case 3:
6303           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6304           break;
6305       }
6306     }
6307
6308     bool Reverse1 = (NonZeros & 0x3) == 2;
6309     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6310     int MaskVec[] = {
6311       Reverse1 ? 1 : 0,
6312       Reverse1 ? 0 : 1,
6313       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6314       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6315     };
6316     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6317   }
6318
6319   if (Values.size() > 1 && VT.is128BitVector()) {
6320     // Check for a build vector of consecutive loads.
6321     for (unsigned i = 0; i < NumElems; ++i)
6322       V[i] = Op.getOperand(i);
6323
6324     // Check for elements which are consecutive loads.
6325     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6326       return LD;
6327
6328     // Check for a build vector from mostly shuffle plus few inserting.
6329     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6330       return Sh;
6331
6332     // For SSE 4.1, use insertps to put the high elements into the low element.
6333     if (Subtarget->hasSSE41()) {
6334       SDValue Result;
6335       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6336         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6337       else
6338         Result = DAG.getUNDEF(VT);
6339
6340       for (unsigned i = 1; i < NumElems; ++i) {
6341         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6342         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6343                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6344       }
6345       return Result;
6346     }
6347
6348     // Otherwise, expand into a number of unpckl*, start by extending each of
6349     // our (non-undef) elements to the full vector width with the element in the
6350     // bottom slot of the vector (which generates no code for SSE).
6351     for (unsigned i = 0; i < NumElems; ++i) {
6352       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6353         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6354       else
6355         V[i] = DAG.getUNDEF(VT);
6356     }
6357
6358     // Next, we iteratively mix elements, e.g. for v4f32:
6359     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6360     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6361     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6362     unsigned EltStride = NumElems >> 1;
6363     while (EltStride != 0) {
6364       for (unsigned i = 0; i < EltStride; ++i) {
6365         // If V[i+EltStride] is undef and this is the first round of mixing,
6366         // then it is safe to just drop this shuffle: V[i] is already in the
6367         // right place, the one element (since it's the first round) being
6368         // inserted as undef can be dropped.  This isn't safe for successive
6369         // rounds because they will permute elements within both vectors.
6370         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6371             EltStride == NumElems/2)
6372           continue;
6373
6374         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6375       }
6376       EltStride >>= 1;
6377     }
6378     return V[0];
6379   }
6380   return SDValue();
6381 }
6382
6383 // 256-bit AVX can use the vinsertf128 instruction
6384 // to create 256-bit vectors from two other 128-bit ones.
6385 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6386   SDLoc dl(Op);
6387   MVT ResVT = Op.getSimpleValueType();
6388
6389   assert((ResVT.is256BitVector() ||
6390           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6391
6392   SDValue V1 = Op.getOperand(0);
6393   SDValue V2 = Op.getOperand(1);
6394   unsigned NumElems = ResVT.getVectorNumElements();
6395   if (ResVT.is256BitVector())
6396     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6397
6398   if (Op.getNumOperands() == 4) {
6399     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6400                                 ResVT.getVectorNumElements()/2);
6401     SDValue V3 = Op.getOperand(2);
6402     SDValue V4 = Op.getOperand(3);
6403     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6404       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6405   }
6406   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6407 }
6408
6409 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6410                                        const X86Subtarget *Subtarget,
6411                                        SelectionDAG & DAG) {
6412   SDLoc dl(Op);
6413   MVT ResVT = Op.getSimpleValueType();
6414   unsigned NumOfOperands = Op.getNumOperands();
6415
6416   assert(isPowerOf2_32(NumOfOperands) &&
6417          "Unexpected number of operands in CONCAT_VECTORS");
6418
6419   if (NumOfOperands > 2) {
6420     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6421                                   ResVT.getVectorNumElements()/2);
6422     SmallVector<SDValue, 2> Ops;
6423     for (unsigned i = 0; i < NumOfOperands/2; i++)
6424       Ops.push_back(Op.getOperand(i));
6425     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6426     Ops.clear();
6427     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6428       Ops.push_back(Op.getOperand(i));
6429     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6430     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6431   }
6432
6433   SDValue V1 = Op.getOperand(0);
6434   SDValue V2 = Op.getOperand(1);
6435   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6436   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6437
6438   if (IsZeroV1 && IsZeroV2)
6439     return getZeroVector(ResVT, Subtarget, DAG, dl);
6440
6441   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6442   SDValue Undef = DAG.getUNDEF(ResVT);
6443   unsigned NumElems = ResVT.getVectorNumElements();
6444   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6445
6446   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6447   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6448   if (IsZeroV1)
6449     return V2;
6450
6451   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6452   // Zero the upper bits of V1
6453   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6454   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6455   if (IsZeroV2)
6456     return V1;
6457   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6458 }
6459
6460 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6461                                    const X86Subtarget *Subtarget,
6462                                    SelectionDAG &DAG) {
6463   MVT VT = Op.getSimpleValueType();
6464   if (VT.getVectorElementType() == MVT::i1)
6465     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6466
6467   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6468          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6469           Op.getNumOperands() == 4)));
6470
6471   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6472   // from two other 128-bit ones.
6473
6474   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6475   return LowerAVXCONCAT_VECTORS(Op, DAG);
6476 }
6477
6478
6479 //===----------------------------------------------------------------------===//
6480 // Vector shuffle lowering
6481 //
6482 // This is an experimental code path for lowering vector shuffles on x86. It is
6483 // designed to handle arbitrary vector shuffles and blends, gracefully
6484 // degrading performance as necessary. It works hard to recognize idiomatic
6485 // shuffles and lower them to optimal instruction patterns without leaving
6486 // a framework that allows reasonably efficient handling of all vector shuffle
6487 // patterns.
6488 //===----------------------------------------------------------------------===//
6489
6490 /// \brief Tiny helper function to identify a no-op mask.
6491 ///
6492 /// This is a somewhat boring predicate function. It checks whether the mask
6493 /// array input, which is assumed to be a single-input shuffle mask of the kind
6494 /// used by the X86 shuffle instructions (not a fully general
6495 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6496 /// in-place shuffle are 'no-op's.
6497 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6498   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6499     if (Mask[i] != -1 && Mask[i] != i)
6500       return false;
6501   return true;
6502 }
6503
6504 /// \brief Helper function to classify a mask as a single-input mask.
6505 ///
6506 /// This isn't a generic single-input test because in the vector shuffle
6507 /// lowering we canonicalize single inputs to be the first input operand. This
6508 /// means we can more quickly test for a single input by only checking whether
6509 /// an input from the second operand exists. We also assume that the size of
6510 /// mask corresponds to the size of the input vectors which isn't true in the
6511 /// fully general case.
6512 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6513   for (int M : Mask)
6514     if (M >= (int)Mask.size())
6515       return false;
6516   return true;
6517 }
6518
6519 /// \brief Test whether there are elements crossing 128-bit lanes in this
6520 /// shuffle mask.
6521 ///
6522 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6523 /// and we routinely test for these.
6524 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6525   int LaneSize = 128 / VT.getScalarSizeInBits();
6526   int Size = Mask.size();
6527   for (int i = 0; i < Size; ++i)
6528     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6529       return true;
6530   return false;
6531 }
6532
6533 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6534 ///
6535 /// This checks a shuffle mask to see if it is performing the same
6536 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6537 /// that it is also not lane-crossing. It may however involve a blend from the
6538 /// same lane of a second vector.
6539 ///
6540 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6541 /// non-trivial to compute in the face of undef lanes. The representation is
6542 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6543 /// entries from both V1 and V2 inputs to the wider mask.
6544 static bool
6545 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6546                                 SmallVectorImpl<int> &RepeatedMask) {
6547   int LaneSize = 128 / VT.getScalarSizeInBits();
6548   RepeatedMask.resize(LaneSize, -1);
6549   int Size = Mask.size();
6550   for (int i = 0; i < Size; ++i) {
6551     if (Mask[i] < 0)
6552       continue;
6553     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6554       // This entry crosses lanes, so there is no way to model this shuffle.
6555       return false;
6556
6557     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6558     if (RepeatedMask[i % LaneSize] == -1)
6559       // This is the first non-undef entry in this slot of a 128-bit lane.
6560       RepeatedMask[i % LaneSize] =
6561           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6562     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6563       // Found a mismatch with the repeated mask.
6564       return false;
6565   }
6566   return true;
6567 }
6568
6569 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6570 /// arguments.
6571 ///
6572 /// This is a fast way to test a shuffle mask against a fixed pattern:
6573 ///
6574 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6575 ///
6576 /// It returns true if the mask is exactly as wide as the argument list, and
6577 /// each element of the mask is either -1 (signifying undef) or the value given
6578 /// in the argument.
6579 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6580                                 ArrayRef<int> ExpectedMask) {
6581   if (Mask.size() != ExpectedMask.size())
6582     return false;
6583
6584   int Size = Mask.size();
6585
6586   // If the values are build vectors, we can look through them to find
6587   // equivalent inputs that make the shuffles equivalent.
6588   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6589   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6590
6591   for (int i = 0; i < Size; ++i)
6592     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6593       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6594       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6595       if (!MaskBV || !ExpectedBV ||
6596           MaskBV->getOperand(Mask[i] % Size) !=
6597               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6598         return false;
6599     }
6600
6601   return true;
6602 }
6603
6604 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6605 ///
6606 /// This helper function produces an 8-bit shuffle immediate corresponding to
6607 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6608 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6609 /// example.
6610 ///
6611 /// NB: We rely heavily on "undef" masks preserving the input lane.
6612 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6613                                           SelectionDAG &DAG) {
6614   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6615   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6616   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6617   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6618   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6619
6620   unsigned Imm = 0;
6621   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6622   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6623   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6624   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6625   return DAG.getConstant(Imm, DL, MVT::i8);
6626 }
6627
6628 /// \brief Compute whether each element of a shuffle is zeroable.
6629 ///
6630 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6631 /// Either it is an undef element in the shuffle mask, the element of the input
6632 /// referenced is undef, or the element of the input referenced is known to be
6633 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6634 /// as many lanes with this technique as possible to simplify the remaining
6635 /// shuffle.
6636 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6637                                                      SDValue V1, SDValue V2) {
6638   SmallBitVector Zeroable(Mask.size(), false);
6639
6640   while (V1.getOpcode() == ISD::BITCAST)
6641     V1 = V1->getOperand(0);
6642   while (V2.getOpcode() == ISD::BITCAST)
6643     V2 = V2->getOperand(0);
6644
6645   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6646   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6647
6648   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6649     int M = Mask[i];
6650     // Handle the easy cases.
6651     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6652       Zeroable[i] = true;
6653       continue;
6654     }
6655
6656     // If this is an index into a build_vector node (which has the same number
6657     // of elements), dig out the input value and use it.
6658     SDValue V = M < Size ? V1 : V2;
6659     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6660       continue;
6661
6662     SDValue Input = V.getOperand(M % Size);
6663     // The UNDEF opcode check really should be dead code here, but not quite
6664     // worth asserting on (it isn't invalid, just unexpected).
6665     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6666       Zeroable[i] = true;
6667   }
6668
6669   return Zeroable;
6670 }
6671
6672 /// \brief Try to emit a bitmask instruction for a shuffle.
6673 ///
6674 /// This handles cases where we can model a blend exactly as a bitmask due to
6675 /// one of the inputs being zeroable.
6676 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6677                                            SDValue V2, ArrayRef<int> Mask,
6678                                            SelectionDAG &DAG) {
6679   MVT EltVT = VT.getScalarType();
6680   int NumEltBits = EltVT.getSizeInBits();
6681   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6682   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6683   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6684                                     IntEltVT);
6685   if (EltVT.isFloatingPoint()) {
6686     Zero = DAG.getBitcast(EltVT, Zero);
6687     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6688   }
6689   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6690   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6691   SDValue V;
6692   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6693     if (Zeroable[i])
6694       continue;
6695     if (Mask[i] % Size != i)
6696       return SDValue(); // Not a blend.
6697     if (!V)
6698       V = Mask[i] < Size ? V1 : V2;
6699     else if (V != (Mask[i] < Size ? V1 : V2))
6700       return SDValue(); // Can only let one input through the mask.
6701
6702     VMaskOps[i] = AllOnes;
6703   }
6704   if (!V)
6705     return SDValue(); // No non-zeroable elements!
6706
6707   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6708   V = DAG.getNode(VT.isFloatingPoint()
6709                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6710                   DL, VT, V, VMask);
6711   return V;
6712 }
6713
6714 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6715 ///
6716 /// This is used as a fallback approach when first class blend instructions are
6717 /// unavailable. Currently it is only suitable for integer vectors, but could
6718 /// be generalized for floating point vectors if desirable.
6719 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6720                                             SDValue V2, ArrayRef<int> Mask,
6721                                             SelectionDAG &DAG) {
6722   assert(VT.isInteger() && "Only supports integer vector types!");
6723   MVT EltVT = VT.getScalarType();
6724   int NumEltBits = EltVT.getSizeInBits();
6725   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6726   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6727                                     EltVT);
6728   SmallVector<SDValue, 16> MaskOps;
6729   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6730     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6731       return SDValue(); // Shuffled input!
6732     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6733   }
6734
6735   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6736   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6737   // We have to cast V2 around.
6738   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6739   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6740                                       DAG.getBitcast(MaskVT, V1Mask),
6741                                       DAG.getBitcast(MaskVT, V2)));
6742   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6743 }
6744
6745 /// \brief Try to emit a blend instruction for a shuffle.
6746 ///
6747 /// This doesn't do any checks for the availability of instructions for blending
6748 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6749 /// be matched in the backend with the type given. What it does check for is
6750 /// that the shuffle mask is in fact a blend.
6751 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6752                                          SDValue V2, ArrayRef<int> Mask,
6753                                          const X86Subtarget *Subtarget,
6754                                          SelectionDAG &DAG) {
6755   unsigned BlendMask = 0;
6756   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6757     if (Mask[i] >= Size) {
6758       if (Mask[i] != i + Size)
6759         return SDValue(); // Shuffled V2 input!
6760       BlendMask |= 1u << i;
6761       continue;
6762     }
6763     if (Mask[i] >= 0 && Mask[i] != i)
6764       return SDValue(); // Shuffled V1 input!
6765   }
6766   switch (VT.SimpleTy) {
6767   case MVT::v2f64:
6768   case MVT::v4f32:
6769   case MVT::v4f64:
6770   case MVT::v8f32:
6771     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6772                        DAG.getConstant(BlendMask, DL, MVT::i8));
6773
6774   case MVT::v4i64:
6775   case MVT::v8i32:
6776     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6777     // FALLTHROUGH
6778   case MVT::v2i64:
6779   case MVT::v4i32:
6780     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6781     // that instruction.
6782     if (Subtarget->hasAVX2()) {
6783       // Scale the blend by the number of 32-bit dwords per element.
6784       int Scale =  VT.getScalarSizeInBits() / 32;
6785       BlendMask = 0;
6786       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6787         if (Mask[i] >= Size)
6788           for (int j = 0; j < Scale; ++j)
6789             BlendMask |= 1u << (i * Scale + j);
6790
6791       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6792       V1 = DAG.getBitcast(BlendVT, V1);
6793       V2 = DAG.getBitcast(BlendVT, V2);
6794       return DAG.getBitcast(
6795           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6796                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6797     }
6798     // FALLTHROUGH
6799   case MVT::v8i16: {
6800     // For integer shuffles we need to expand the mask and cast the inputs to
6801     // v8i16s prior to blending.
6802     int Scale = 8 / VT.getVectorNumElements();
6803     BlendMask = 0;
6804     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6805       if (Mask[i] >= Size)
6806         for (int j = 0; j < Scale; ++j)
6807           BlendMask |= 1u << (i * Scale + j);
6808
6809     V1 = DAG.getBitcast(MVT::v8i16, V1);
6810     V2 = DAG.getBitcast(MVT::v8i16, V2);
6811     return DAG.getBitcast(VT,
6812                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6813                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6814   }
6815
6816   case MVT::v16i16: {
6817     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6818     SmallVector<int, 8> RepeatedMask;
6819     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6820       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6821       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6822       BlendMask = 0;
6823       for (int i = 0; i < 8; ++i)
6824         if (RepeatedMask[i] >= 16)
6825           BlendMask |= 1u << i;
6826       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6827                          DAG.getConstant(BlendMask, DL, MVT::i8));
6828     }
6829   }
6830     // FALLTHROUGH
6831   case MVT::v16i8:
6832   case MVT::v32i8: {
6833     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6834            "256-bit byte-blends require AVX2 support!");
6835
6836     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6837     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6838       return Masked;
6839
6840     // Scale the blend by the number of bytes per element.
6841     int Scale = VT.getScalarSizeInBits() / 8;
6842
6843     // This form of blend is always done on bytes. Compute the byte vector
6844     // type.
6845     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6846
6847     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6848     // mix of LLVM's code generator and the x86 backend. We tell the code
6849     // generator that boolean values in the elements of an x86 vector register
6850     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6851     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6852     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6853     // of the element (the remaining are ignored) and 0 in that high bit would
6854     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6855     // the LLVM model for boolean values in vector elements gets the relevant
6856     // bit set, it is set backwards and over constrained relative to x86's
6857     // actual model.
6858     SmallVector<SDValue, 32> VSELECTMask;
6859     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6860       for (int j = 0; j < Scale; ++j)
6861         VSELECTMask.push_back(
6862             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6863                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6864                                           MVT::i8));
6865
6866     V1 = DAG.getBitcast(BlendVT, V1);
6867     V2 = DAG.getBitcast(BlendVT, V2);
6868     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6869                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6870                                                       BlendVT, VSELECTMask),
6871                                           V1, V2));
6872   }
6873
6874   default:
6875     llvm_unreachable("Not a supported integer vector type!");
6876   }
6877 }
6878
6879 /// \brief Try to lower as a blend of elements from two inputs followed by
6880 /// a single-input permutation.
6881 ///
6882 /// This matches the pattern where we can blend elements from two inputs and
6883 /// then reduce the shuffle to a single-input permutation.
6884 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6885                                                    SDValue V2,
6886                                                    ArrayRef<int> Mask,
6887                                                    SelectionDAG &DAG) {
6888   // We build up the blend mask while checking whether a blend is a viable way
6889   // to reduce the shuffle.
6890   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6891   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6892
6893   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6894     if (Mask[i] < 0)
6895       continue;
6896
6897     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6898
6899     if (BlendMask[Mask[i] % Size] == -1)
6900       BlendMask[Mask[i] % Size] = Mask[i];
6901     else if (BlendMask[Mask[i] % Size] != Mask[i])
6902       return SDValue(); // Can't blend in the needed input!
6903
6904     PermuteMask[i] = Mask[i] % Size;
6905   }
6906
6907   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6908   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6909 }
6910
6911 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6912 /// blends and permutes.
6913 ///
6914 /// This matches the extremely common pattern for handling combined
6915 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6916 /// operations. It will try to pick the best arrangement of shuffles and
6917 /// blends.
6918 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6919                                                           SDValue V1,
6920                                                           SDValue V2,
6921                                                           ArrayRef<int> Mask,
6922                                                           SelectionDAG &DAG) {
6923   // Shuffle the input elements into the desired positions in V1 and V2 and
6924   // blend them together.
6925   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6926   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6927   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6928   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6929     if (Mask[i] >= 0 && Mask[i] < Size) {
6930       V1Mask[i] = Mask[i];
6931       BlendMask[i] = i;
6932     } else if (Mask[i] >= Size) {
6933       V2Mask[i] = Mask[i] - Size;
6934       BlendMask[i] = i + Size;
6935     }
6936
6937   // Try to lower with the simpler initial blend strategy unless one of the
6938   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6939   // shuffle may be able to fold with a load or other benefit. However, when
6940   // we'll have to do 2x as many shuffles in order to achieve this, blending
6941   // first is a better strategy.
6942   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6943     if (SDValue BlendPerm =
6944             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6945       return BlendPerm;
6946
6947   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6948   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6949   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6950 }
6951
6952 /// \brief Try to lower a vector shuffle as a byte rotation.
6953 ///
6954 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6955 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6956 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6957 /// try to generically lower a vector shuffle through such an pattern. It
6958 /// does not check for the profitability of lowering either as PALIGNR or
6959 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6960 /// This matches shuffle vectors that look like:
6961 ///
6962 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6963 ///
6964 /// Essentially it concatenates V1 and V2, shifts right by some number of
6965 /// elements, and takes the low elements as the result. Note that while this is
6966 /// specified as a *right shift* because x86 is little-endian, it is a *left
6967 /// rotate* of the vector lanes.
6968 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6969                                               SDValue V2,
6970                                               ArrayRef<int> Mask,
6971                                               const X86Subtarget *Subtarget,
6972                                               SelectionDAG &DAG) {
6973   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6974
6975   int NumElts = Mask.size();
6976   int NumLanes = VT.getSizeInBits() / 128;
6977   int NumLaneElts = NumElts / NumLanes;
6978
6979   // We need to detect various ways of spelling a rotation:
6980   //   [11, 12, 13, 14, 15,  0,  1,  2]
6981   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6982   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6983   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6984   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6985   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6986   int Rotation = 0;
6987   SDValue Lo, Hi;
6988   for (int l = 0; l < NumElts; l += NumLaneElts) {
6989     for (int i = 0; i < NumLaneElts; ++i) {
6990       if (Mask[l + i] == -1)
6991         continue;
6992       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6993
6994       // Get the mod-Size index and lane correct it.
6995       int LaneIdx = (Mask[l + i] % NumElts) - l;
6996       // Make sure it was in this lane.
6997       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6998         return SDValue();
6999
7000       // Determine where a rotated vector would have started.
7001       int StartIdx = i - LaneIdx;
7002       if (StartIdx == 0)
7003         // The identity rotation isn't interesting, stop.
7004         return SDValue();
7005
7006       // If we found the tail of a vector the rotation must be the missing
7007       // front. If we found the head of a vector, it must be how much of the
7008       // head.
7009       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7010
7011       if (Rotation == 0)
7012         Rotation = CandidateRotation;
7013       else if (Rotation != CandidateRotation)
7014         // The rotations don't match, so we can't match this mask.
7015         return SDValue();
7016
7017       // Compute which value this mask is pointing at.
7018       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7019
7020       // Compute which of the two target values this index should be assigned
7021       // to. This reflects whether the high elements are remaining or the low
7022       // elements are remaining.
7023       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7024
7025       // Either set up this value if we've not encountered it before, or check
7026       // that it remains consistent.
7027       if (!TargetV)
7028         TargetV = MaskV;
7029       else if (TargetV != MaskV)
7030         // This may be a rotation, but it pulls from the inputs in some
7031         // unsupported interleaving.
7032         return SDValue();
7033     }
7034   }
7035
7036   // Check that we successfully analyzed the mask, and normalize the results.
7037   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7038   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7039   if (!Lo)
7040     Lo = Hi;
7041   else if (!Hi)
7042     Hi = Lo;
7043
7044   // The actual rotate instruction rotates bytes, so we need to scale the
7045   // rotation based on how many bytes are in the vector lane.
7046   int Scale = 16 / NumLaneElts;
7047
7048   // SSSE3 targets can use the palignr instruction.
7049   if (Subtarget->hasSSSE3()) {
7050     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7051     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7052     Lo = DAG.getBitcast(AlignVT, Lo);
7053     Hi = DAG.getBitcast(AlignVT, Hi);
7054
7055     return DAG.getBitcast(
7056         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7057                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7058   }
7059
7060   assert(VT.getSizeInBits() == 128 &&
7061          "Rotate-based lowering only supports 128-bit lowering!");
7062   assert(Mask.size() <= 16 &&
7063          "Can shuffle at most 16 bytes in a 128-bit vector!");
7064
7065   // Default SSE2 implementation
7066   int LoByteShift = 16 - Rotation * Scale;
7067   int HiByteShift = Rotation * Scale;
7068
7069   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7070   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7071   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7072
7073   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7074                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7075   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7076                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7077   return DAG.getBitcast(VT,
7078                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7079 }
7080
7081 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7082 ///
7083 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7084 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7085 /// matches elements from one of the input vectors shuffled to the left or
7086 /// right with zeroable elements 'shifted in'. It handles both the strictly
7087 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7088 /// quad word lane.
7089 ///
7090 /// PSHL : (little-endian) left bit shift.
7091 /// [ zz, 0, zz,  2 ]
7092 /// [ -1, 4, zz, -1 ]
7093 /// PSRL : (little-endian) right bit shift.
7094 /// [  1, zz,  3, zz]
7095 /// [ -1, -1,  7, zz]
7096 /// PSLLDQ : (little-endian) left byte shift
7097 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7098 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7099 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7100 /// PSRLDQ : (little-endian) right byte shift
7101 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7102 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7103 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7104 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7105                                          SDValue V2, ArrayRef<int> Mask,
7106                                          SelectionDAG &DAG) {
7107   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7108
7109   int Size = Mask.size();
7110   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7111
7112   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7113     for (int i = 0; i < Size; i += Scale)
7114       for (int j = 0; j < Shift; ++j)
7115         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7116           return false;
7117
7118     return true;
7119   };
7120
7121   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7122     for (int i = 0; i != Size; i += Scale) {
7123       unsigned Pos = Left ? i + Shift : i;
7124       unsigned Low = Left ? i : i + Shift;
7125       unsigned Len = Scale - Shift;
7126       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7127                                       Low + (V == V1 ? 0 : Size)))
7128         return SDValue();
7129     }
7130
7131     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7132     bool ByteShift = ShiftEltBits > 64;
7133     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7134                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7135     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7136
7137     // Normalize the scale for byte shifts to still produce an i64 element
7138     // type.
7139     Scale = ByteShift ? Scale / 2 : Scale;
7140
7141     // We need to round trip through the appropriate type for the shift.
7142     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7143     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7144     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7145            "Illegal integer vector type");
7146     V = DAG.getBitcast(ShiftVT, V);
7147
7148     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7149                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7150     return DAG.getBitcast(VT, V);
7151   };
7152
7153   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7154   // keep doubling the size of the integer elements up to that. We can
7155   // then shift the elements of the integer vector by whole multiples of
7156   // their width within the elements of the larger integer vector. Test each
7157   // multiple to see if we can find a match with the moved element indices
7158   // and that the shifted in elements are all zeroable.
7159   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7160     for (int Shift = 1; Shift != Scale; ++Shift)
7161       for (bool Left : {true, false})
7162         if (CheckZeros(Shift, Scale, Left))
7163           for (SDValue V : {V1, V2})
7164             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7165               return Match;
7166
7167   // no match
7168   return SDValue();
7169 }
7170
7171 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7172 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7173                                            SDValue V2, ArrayRef<int> Mask,
7174                                            SelectionDAG &DAG) {
7175   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7176   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7177
7178   int Size = Mask.size();
7179   int HalfSize = Size / 2;
7180   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7181
7182   // Upper half must be undefined.
7183   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7184     return SDValue();
7185
7186   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7187   // Remainder of lower half result is zero and upper half is all undef.
7188   auto LowerAsEXTRQ = [&]() {
7189     // Determine the extraction length from the part of the
7190     // lower half that isn't zeroable.
7191     int Len = HalfSize;
7192     for (; Len >= 0; --Len)
7193       if (!Zeroable[Len - 1])
7194         break;
7195     assert(Len > 0 && "Zeroable shuffle mask");
7196
7197     // Attempt to match first Len sequential elements from the lower half.
7198     SDValue Src;
7199     int Idx = -1;
7200     for (int i = 0; i != Len; ++i) {
7201       int M = Mask[i];
7202       if (M < 0)
7203         continue;
7204       SDValue &V = (M < Size ? V1 : V2);
7205       M = M % Size;
7206
7207       // All mask elements must be in the lower half.
7208       if (M > HalfSize)
7209         return SDValue();
7210
7211       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7212         Src = V;
7213         Idx = M - i;
7214         continue;
7215       }
7216       return SDValue();
7217     }
7218
7219     if (Idx < 0)
7220       return SDValue();
7221
7222     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7223     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7224     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7225     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7226                        DAG.getConstant(BitLen, DL, MVT::i8),
7227                        DAG.getConstant(BitIdx, DL, MVT::i8));
7228   };
7229
7230   if (SDValue ExtrQ = LowerAsEXTRQ())
7231     return ExtrQ;
7232
7233   // INSERTQ: Extract lowest Len elements from lower half of second source and
7234   // insert over first source, starting at Idx.
7235   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7236   auto LowerAsInsertQ = [&]() {
7237     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7238       SDValue Base;
7239
7240       // Attempt to match first source from mask before insertion point.
7241       if (isUndefInRange(Mask, 0, Idx)) {
7242         /* EMPTY */
7243       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7244         Base = V1;
7245       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7246         Base = V2;
7247       } else {
7248         continue;
7249       }
7250
7251       // Extend the extraction length looking to match both the insertion of
7252       // the second source and the remaining elements of the first.
7253       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7254         SDValue Insert;
7255         int Len = Hi - Idx;
7256
7257         // Match insertion.
7258         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7259           Insert = V1;
7260         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7261           Insert = V2;
7262         } else {
7263           continue;
7264         }
7265
7266         // Match the remaining elements of the lower half.
7267         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7268           /* EMPTY */
7269         } else if ((!Base || (Base == V1)) &&
7270                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7271           Base = V1;
7272         } else if ((!Base || (Base == V2)) &&
7273                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7274                                               Size + Hi)) {
7275           Base = V2;
7276         } else {
7277           continue;
7278         }
7279
7280         // We may not have a base (first source) - this can safely be undefined.
7281         if (!Base)
7282           Base = DAG.getUNDEF(VT);
7283
7284         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7285         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7286         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7287                            DAG.getConstant(BitLen, DL, MVT::i8),
7288                            DAG.getConstant(BitIdx, DL, MVT::i8));
7289       }
7290     }
7291
7292     return SDValue();
7293   };
7294
7295   if (SDValue InsertQ = LowerAsInsertQ())
7296     return InsertQ;
7297
7298   return SDValue();
7299 }
7300
7301 /// \brief Lower a vector shuffle as a zero or any extension.
7302 ///
7303 /// Given a specific number of elements, element bit width, and extension
7304 /// stride, produce either a zero or any extension based on the available
7305 /// features of the subtarget.
7306 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7307     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7308     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7309   assert(Scale > 1 && "Need a scale to extend.");
7310   int NumElements = VT.getVectorNumElements();
7311   int EltBits = VT.getScalarSizeInBits();
7312   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7313          "Only 8, 16, and 32 bit elements can be extended.");
7314   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7315
7316   // Found a valid zext mask! Try various lowering strategies based on the
7317   // input type and available ISA extensions.
7318   if (Subtarget->hasSSE41()) {
7319     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7320                                  NumElements / Scale);
7321     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7322   }
7323
7324   // For any extends we can cheat for larger element sizes and use shuffle
7325   // instructions that can fold with a load and/or copy.
7326   if (AnyExt && EltBits == 32) {
7327     int PSHUFDMask[4] = {0, -1, 1, -1};
7328     return DAG.getBitcast(
7329         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7330                         DAG.getBitcast(MVT::v4i32, InputV),
7331                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7332   }
7333   if (AnyExt && EltBits == 16 && Scale > 2) {
7334     int PSHUFDMask[4] = {0, -1, 0, -1};
7335     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7336                          DAG.getBitcast(MVT::v4i32, InputV),
7337                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7338     int PSHUFHWMask[4] = {1, -1, -1, -1};
7339     return DAG.getBitcast(
7340         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7341                         DAG.getBitcast(MVT::v8i16, InputV),
7342                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7343   }
7344
7345   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7346   // to 64-bits.
7347   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7348     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7349     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7350
7351     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7352                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7353                                          DAG.getConstant(EltBits, DL, MVT::i8),
7354                                          DAG.getConstant(0, DL, MVT::i8)));
7355     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7356       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7357
7358     SDValue Hi =
7359         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7360                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7361                                 DAG.getConstant(EltBits, DL, MVT::i8),
7362                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7363     return DAG.getNode(ISD::BITCAST, DL, VT,
7364                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7365   }
7366
7367   // If this would require more than 2 unpack instructions to expand, use
7368   // pshufb when available. We can only use more than 2 unpack instructions
7369   // when zero extending i8 elements which also makes it easier to use pshufb.
7370   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7371     assert(NumElements == 16 && "Unexpected byte vector width!");
7372     SDValue PSHUFBMask[16];
7373     for (int i = 0; i < 16; ++i)
7374       PSHUFBMask[i] =
7375           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7376     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7377     return DAG.getBitcast(VT,
7378                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7379                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7380                                                   MVT::v16i8, PSHUFBMask)));
7381   }
7382
7383   // Otherwise emit a sequence of unpacks.
7384   do {
7385     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7386     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7387                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7388     InputV = DAG.getBitcast(InputVT, InputV);
7389     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7390     Scale /= 2;
7391     EltBits *= 2;
7392     NumElements /= 2;
7393   } while (Scale > 1);
7394   return DAG.getBitcast(VT, InputV);
7395 }
7396
7397 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7398 ///
7399 /// This routine will try to do everything in its power to cleverly lower
7400 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7401 /// check for the profitability of this lowering,  it tries to aggressively
7402 /// match this pattern. It will use all of the micro-architectural details it
7403 /// can to emit an efficient lowering. It handles both blends with all-zero
7404 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7405 /// masking out later).
7406 ///
7407 /// The reason we have dedicated lowering for zext-style shuffles is that they
7408 /// are both incredibly common and often quite performance sensitive.
7409 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7410     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7411     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7412   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7413
7414   int Bits = VT.getSizeInBits();
7415   int NumElements = VT.getVectorNumElements();
7416   assert(VT.getScalarSizeInBits() <= 32 &&
7417          "Exceeds 32-bit integer zero extension limit");
7418   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7419
7420   // Define a helper function to check a particular ext-scale and lower to it if
7421   // valid.
7422   auto Lower = [&](int Scale) -> SDValue {
7423     SDValue InputV;
7424     bool AnyExt = true;
7425     for (int i = 0; i < NumElements; ++i) {
7426       if (Mask[i] == -1)
7427         continue; // Valid anywhere but doesn't tell us anything.
7428       if (i % Scale != 0) {
7429         // Each of the extended elements need to be zeroable.
7430         if (!Zeroable[i])
7431           return SDValue();
7432
7433         // We no longer are in the anyext case.
7434         AnyExt = false;
7435         continue;
7436       }
7437
7438       // Each of the base elements needs to be consecutive indices into the
7439       // same input vector.
7440       SDValue V = Mask[i] < NumElements ? V1 : V2;
7441       if (!InputV)
7442         InputV = V;
7443       else if (InputV != V)
7444         return SDValue(); // Flip-flopping inputs.
7445
7446       if (Mask[i] % NumElements != i / Scale)
7447         return SDValue(); // Non-consecutive strided elements.
7448     }
7449
7450     // If we fail to find an input, we have a zero-shuffle which should always
7451     // have already been handled.
7452     // FIXME: Maybe handle this here in case during blending we end up with one?
7453     if (!InputV)
7454       return SDValue();
7455
7456     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7457         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7458   };
7459
7460   // The widest scale possible for extending is to a 64-bit integer.
7461   assert(Bits % 64 == 0 &&
7462          "The number of bits in a vector must be divisible by 64 on x86!");
7463   int NumExtElements = Bits / 64;
7464
7465   // Each iteration, try extending the elements half as much, but into twice as
7466   // many elements.
7467   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7468     assert(NumElements % NumExtElements == 0 &&
7469            "The input vector size must be divisible by the extended size.");
7470     if (SDValue V = Lower(NumElements / NumExtElements))
7471       return V;
7472   }
7473
7474   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7475   if (Bits != 128)
7476     return SDValue();
7477
7478   // Returns one of the source operands if the shuffle can be reduced to a
7479   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7480   auto CanZExtLowHalf = [&]() {
7481     for (int i = NumElements / 2; i != NumElements; ++i)
7482       if (!Zeroable[i])
7483         return SDValue();
7484     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7485       return V1;
7486     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7487       return V2;
7488     return SDValue();
7489   };
7490
7491   if (SDValue V = CanZExtLowHalf()) {
7492     V = DAG.getBitcast(MVT::v2i64, V);
7493     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7494     return DAG.getBitcast(VT, V);
7495   }
7496
7497   // No viable ext lowering found.
7498   return SDValue();
7499 }
7500
7501 /// \brief Try to get a scalar value for a specific element of a vector.
7502 ///
7503 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7504 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7505                                               SelectionDAG &DAG) {
7506   MVT VT = V.getSimpleValueType();
7507   MVT EltVT = VT.getVectorElementType();
7508   while (V.getOpcode() == ISD::BITCAST)
7509     V = V.getOperand(0);
7510   // If the bitcasts shift the element size, we can't extract an equivalent
7511   // element from it.
7512   MVT NewVT = V.getSimpleValueType();
7513   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7514     return SDValue();
7515
7516   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7517       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7518     // Ensure the scalar operand is the same size as the destination.
7519     // FIXME: Add support for scalar truncation where possible.
7520     SDValue S = V.getOperand(Idx);
7521     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7522       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7523   }
7524
7525   return SDValue();
7526 }
7527
7528 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7529 ///
7530 /// This is particularly important because the set of instructions varies
7531 /// significantly based on whether the operand is a load or not.
7532 static bool isShuffleFoldableLoad(SDValue V) {
7533   while (V.getOpcode() == ISD::BITCAST)
7534     V = V.getOperand(0);
7535
7536   return ISD::isNON_EXTLoad(V.getNode());
7537 }
7538
7539 /// \brief Try to lower insertion of a single element into a zero vector.
7540 ///
7541 /// This is a common pattern that we have especially efficient patterns to lower
7542 /// across all subtarget feature sets.
7543 static SDValue lowerVectorShuffleAsElementInsertion(
7544     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7545     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7546   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7547   MVT ExtVT = VT;
7548   MVT EltVT = VT.getVectorElementType();
7549
7550   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7551                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7552                 Mask.begin();
7553   bool IsV1Zeroable = true;
7554   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7555     if (i != V2Index && !Zeroable[i]) {
7556       IsV1Zeroable = false;
7557       break;
7558     }
7559
7560   // Check for a single input from a SCALAR_TO_VECTOR node.
7561   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7562   // all the smarts here sunk into that routine. However, the current
7563   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7564   // vector shuffle lowering is dead.
7565   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7566                                                DAG);
7567   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7568     // We need to zext the scalar if it is smaller than an i32.
7569     V2S = DAG.getBitcast(EltVT, V2S);
7570     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7571       // Using zext to expand a narrow element won't work for non-zero
7572       // insertions.
7573       if (!IsV1Zeroable)
7574         return SDValue();
7575
7576       // Zero-extend directly to i32.
7577       ExtVT = MVT::v4i32;
7578       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7579     }
7580     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7581   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7582              EltVT == MVT::i16) {
7583     // Either not inserting from the low element of the input or the input
7584     // element size is too small to use VZEXT_MOVL to clear the high bits.
7585     return SDValue();
7586   }
7587
7588   if (!IsV1Zeroable) {
7589     // If V1 can't be treated as a zero vector we have fewer options to lower
7590     // this. We can't support integer vectors or non-zero targets cheaply, and
7591     // the V1 elements can't be permuted in any way.
7592     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7593     if (!VT.isFloatingPoint() || V2Index != 0)
7594       return SDValue();
7595     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7596     V1Mask[V2Index] = -1;
7597     if (!isNoopShuffleMask(V1Mask))
7598       return SDValue();
7599     // This is essentially a special case blend operation, but if we have
7600     // general purpose blend operations, they are always faster. Bail and let
7601     // the rest of the lowering handle these as blends.
7602     if (Subtarget->hasSSE41())
7603       return SDValue();
7604
7605     // Otherwise, use MOVSD or MOVSS.
7606     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7607            "Only two types of floating point element types to handle!");
7608     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7609                        ExtVT, V1, V2);
7610   }
7611
7612   // This lowering only works for the low element with floating point vectors.
7613   if (VT.isFloatingPoint() && V2Index != 0)
7614     return SDValue();
7615
7616   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7617   if (ExtVT != VT)
7618     V2 = DAG.getBitcast(VT, V2);
7619
7620   if (V2Index != 0) {
7621     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7622     // the desired position. Otherwise it is more efficient to do a vector
7623     // shift left. We know that we can do a vector shift left because all
7624     // the inputs are zero.
7625     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7626       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7627       V2Shuffle[V2Index] = 0;
7628       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7629     } else {
7630       V2 = DAG.getBitcast(MVT::v2i64, V2);
7631       V2 = DAG.getNode(
7632           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7633           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7634                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7635                               DAG.getDataLayout(), VT)));
7636       V2 = DAG.getBitcast(VT, V2);
7637     }
7638   }
7639   return V2;
7640 }
7641
7642 /// \brief Try to lower broadcast of a single element.
7643 ///
7644 /// For convenience, this code also bundles all of the subtarget feature set
7645 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7646 /// a convenient way to factor it out.
7647 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7648                                              ArrayRef<int> Mask,
7649                                              const X86Subtarget *Subtarget,
7650                                              SelectionDAG &DAG) {
7651   if (!Subtarget->hasAVX())
7652     return SDValue();
7653   if (VT.isInteger() && !Subtarget->hasAVX2())
7654     return SDValue();
7655
7656   // Check that the mask is a broadcast.
7657   int BroadcastIdx = -1;
7658   for (int M : Mask)
7659     if (M >= 0 && BroadcastIdx == -1)
7660       BroadcastIdx = M;
7661     else if (M >= 0 && M != BroadcastIdx)
7662       return SDValue();
7663
7664   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7665                                             "a sorted mask where the broadcast "
7666                                             "comes from V1.");
7667
7668   // Go up the chain of (vector) values to find a scalar load that we can
7669   // combine with the broadcast.
7670   for (;;) {
7671     switch (V.getOpcode()) {
7672     case ISD::CONCAT_VECTORS: {
7673       int OperandSize = Mask.size() / V.getNumOperands();
7674       V = V.getOperand(BroadcastIdx / OperandSize);
7675       BroadcastIdx %= OperandSize;
7676       continue;
7677     }
7678
7679     case ISD::INSERT_SUBVECTOR: {
7680       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7681       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7682       if (!ConstantIdx)
7683         break;
7684
7685       int BeginIdx = (int)ConstantIdx->getZExtValue();
7686       int EndIdx =
7687           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7688       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7689         BroadcastIdx -= BeginIdx;
7690         V = VInner;
7691       } else {
7692         V = VOuter;
7693       }
7694       continue;
7695     }
7696     }
7697     break;
7698   }
7699
7700   // Check if this is a broadcast of a scalar. We special case lowering
7701   // for scalars so that we can more effectively fold with loads.
7702   // First, look through bitcast: if the original value has a larger element
7703   // type than the shuffle, the broadcast element is in essence truncated.
7704   // Make that explicit to ease folding.
7705   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7706     EVT EltVT = VT.getVectorElementType();
7707     SDValue V0 = V.getOperand(0);
7708     EVT V0VT = V0.getValueType();
7709
7710     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7711         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7712          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7713       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7714       BroadcastIdx = 0;
7715     }
7716   }
7717
7718   // Also check the simpler case, where we can directly reuse the scalar.
7719   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7720       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7721     V = V.getOperand(BroadcastIdx);
7722
7723     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7724     // Only AVX2 has register broadcasts.
7725     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7726       return SDValue();
7727   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7728     // We can't broadcast from a vector register without AVX2, and we can only
7729     // broadcast from the zero-element of a vector register.
7730     return SDValue();
7731   }
7732
7733   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7734 }
7735
7736 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7737 // INSERTPS when the V1 elements are already in the correct locations
7738 // because otherwise we can just always use two SHUFPS instructions which
7739 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7740 // perform INSERTPS if a single V1 element is out of place and all V2
7741 // elements are zeroable.
7742 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7743                                             ArrayRef<int> Mask,
7744                                             SelectionDAG &DAG) {
7745   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7746   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7747   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7748   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7749
7750   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7751
7752   unsigned ZMask = 0;
7753   int V1DstIndex = -1;
7754   int V2DstIndex = -1;
7755   bool V1UsedInPlace = false;
7756
7757   for (int i = 0; i < 4; ++i) {
7758     // Synthesize a zero mask from the zeroable elements (includes undefs).
7759     if (Zeroable[i]) {
7760       ZMask |= 1 << i;
7761       continue;
7762     }
7763
7764     // Flag if we use any V1 inputs in place.
7765     if (i == Mask[i]) {
7766       V1UsedInPlace = true;
7767       continue;
7768     }
7769
7770     // We can only insert a single non-zeroable element.
7771     if (V1DstIndex != -1 || V2DstIndex != -1)
7772       return SDValue();
7773
7774     if (Mask[i] < 4) {
7775       // V1 input out of place for insertion.
7776       V1DstIndex = i;
7777     } else {
7778       // V2 input for insertion.
7779       V2DstIndex = i;
7780     }
7781   }
7782
7783   // Don't bother if we have no (non-zeroable) element for insertion.
7784   if (V1DstIndex == -1 && V2DstIndex == -1)
7785     return SDValue();
7786
7787   // Determine element insertion src/dst indices. The src index is from the
7788   // start of the inserted vector, not the start of the concatenated vector.
7789   unsigned V2SrcIndex = 0;
7790   if (V1DstIndex != -1) {
7791     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7792     // and don't use the original V2 at all.
7793     V2SrcIndex = Mask[V1DstIndex];
7794     V2DstIndex = V1DstIndex;
7795     V2 = V1;
7796   } else {
7797     V2SrcIndex = Mask[V2DstIndex] - 4;
7798   }
7799
7800   // If no V1 inputs are used in place, then the result is created only from
7801   // the zero mask and the V2 insertion - so remove V1 dependency.
7802   if (!V1UsedInPlace)
7803     V1 = DAG.getUNDEF(MVT::v4f32);
7804
7805   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7806   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7807
7808   // Insert the V2 element into the desired position.
7809   SDLoc DL(Op);
7810   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7811                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7812 }
7813
7814 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7815 /// UNPCK instruction.
7816 ///
7817 /// This specifically targets cases where we end up with alternating between
7818 /// the two inputs, and so can permute them into something that feeds a single
7819 /// UNPCK instruction. Note that this routine only targets integer vectors
7820 /// because for floating point vectors we have a generalized SHUFPS lowering
7821 /// strategy that handles everything that doesn't *exactly* match an unpack,
7822 /// making this clever lowering unnecessary.
7823 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7824                                           SDValue V2, ArrayRef<int> Mask,
7825                                           SelectionDAG &DAG) {
7826   assert(!VT.isFloatingPoint() &&
7827          "This routine only supports integer vectors.");
7828   assert(!isSingleInputShuffleMask(Mask) &&
7829          "This routine should only be used when blending two inputs.");
7830   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7831
7832   int Size = Mask.size();
7833
7834   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7835     return M >= 0 && M % Size < Size / 2;
7836   });
7837   int NumHiInputs = std::count_if(
7838       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7839
7840   bool UnpackLo = NumLoInputs >= NumHiInputs;
7841
7842   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7843     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7844     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7845
7846     for (int i = 0; i < Size; ++i) {
7847       if (Mask[i] < 0)
7848         continue;
7849
7850       // Each element of the unpack contains Scale elements from this mask.
7851       int UnpackIdx = i / Scale;
7852
7853       // We only handle the case where V1 feeds the first slots of the unpack.
7854       // We rely on canonicalization to ensure this is the case.
7855       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7856         return SDValue();
7857
7858       // Setup the mask for this input. The indexing is tricky as we have to
7859       // handle the unpack stride.
7860       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7861       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7862           Mask[i] % Size;
7863     }
7864
7865     // If we will have to shuffle both inputs to use the unpack, check whether
7866     // we can just unpack first and shuffle the result. If so, skip this unpack.
7867     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7868         !isNoopShuffleMask(V2Mask))
7869       return SDValue();
7870
7871     // Shuffle the inputs into place.
7872     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7873     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7874
7875     // Cast the inputs to the type we will use to unpack them.
7876     V1 = DAG.getBitcast(UnpackVT, V1);
7877     V2 = DAG.getBitcast(UnpackVT, V2);
7878
7879     // Unpack the inputs and cast the result back to the desired type.
7880     return DAG.getBitcast(
7881         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7882                         UnpackVT, V1, V2));
7883   };
7884
7885   // We try each unpack from the largest to the smallest to try and find one
7886   // that fits this mask.
7887   int OrigNumElements = VT.getVectorNumElements();
7888   int OrigScalarSize = VT.getScalarSizeInBits();
7889   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7890     int Scale = ScalarSize / OrigScalarSize;
7891     int NumElements = OrigNumElements / Scale;
7892     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7893     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7894       return Unpack;
7895   }
7896
7897   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7898   // initial unpack.
7899   if (NumLoInputs == 0 || NumHiInputs == 0) {
7900     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7901            "We have to have *some* inputs!");
7902     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7903
7904     // FIXME: We could consider the total complexity of the permute of each
7905     // possible unpacking. Or at the least we should consider how many
7906     // half-crossings are created.
7907     // FIXME: We could consider commuting the unpacks.
7908
7909     SmallVector<int, 32> PermMask;
7910     PermMask.assign(Size, -1);
7911     for (int i = 0; i < Size; ++i) {
7912       if (Mask[i] < 0)
7913         continue;
7914
7915       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7916
7917       PermMask[i] =
7918           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7919     }
7920     return DAG.getVectorShuffle(
7921         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7922                             DL, VT, V1, V2),
7923         DAG.getUNDEF(VT), PermMask);
7924   }
7925
7926   return SDValue();
7927 }
7928
7929 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7930 ///
7931 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7932 /// support for floating point shuffles but not integer shuffles. These
7933 /// instructions will incur a domain crossing penalty on some chips though so
7934 /// it is better to avoid lowering through this for integer vectors where
7935 /// possible.
7936 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7937                                        const X86Subtarget *Subtarget,
7938                                        SelectionDAG &DAG) {
7939   SDLoc DL(Op);
7940   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7941   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7942   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7943   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7944   ArrayRef<int> Mask = SVOp->getMask();
7945   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7946
7947   if (isSingleInputShuffleMask(Mask)) {
7948     // Use low duplicate instructions for masks that match their pattern.
7949     if (Subtarget->hasSSE3())
7950       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7951         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7952
7953     // Straight shuffle of a single input vector. Simulate this by using the
7954     // single input as both of the "inputs" to this instruction..
7955     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7956
7957     if (Subtarget->hasAVX()) {
7958       // If we have AVX, we can use VPERMILPS which will allow folding a load
7959       // into the shuffle.
7960       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7961                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7962     }
7963
7964     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7965                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7966   }
7967   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7968   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7969
7970   // If we have a single input, insert that into V1 if we can do so cheaply.
7971   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7972     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7973             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7974       return Insertion;
7975     // Try inverting the insertion since for v2 masks it is easy to do and we
7976     // can't reliably sort the mask one way or the other.
7977     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7978                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7979     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7980             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7981       return Insertion;
7982   }
7983
7984   // Try to use one of the special instruction patterns to handle two common
7985   // blend patterns if a zero-blend above didn't work.
7986   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7987       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7988     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7989       // We can either use a special instruction to load over the low double or
7990       // to move just the low double.
7991       return DAG.getNode(
7992           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7993           DL, MVT::v2f64, V2,
7994           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7995
7996   if (Subtarget->hasSSE41())
7997     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7998                                                   Subtarget, DAG))
7999       return Blend;
8000
8001   // Use dedicated unpack instructions for masks that match their pattern.
8002   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8003     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8004   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8005     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8006
8007   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8008   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8009                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8010 }
8011
8012 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8013 ///
8014 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8015 /// the integer unit to minimize domain crossing penalties. However, for blends
8016 /// it falls back to the floating point shuffle operation with appropriate bit
8017 /// casting.
8018 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8019                                        const X86Subtarget *Subtarget,
8020                                        SelectionDAG &DAG) {
8021   SDLoc DL(Op);
8022   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8023   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8024   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8025   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8026   ArrayRef<int> Mask = SVOp->getMask();
8027   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8028
8029   if (isSingleInputShuffleMask(Mask)) {
8030     // Check for being able to broadcast a single element.
8031     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8032                                                           Mask, Subtarget, DAG))
8033       return Broadcast;
8034
8035     // Straight shuffle of a single input vector. For everything from SSE2
8036     // onward this has a single fast instruction with no scary immediates.
8037     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8038     V1 = DAG.getBitcast(MVT::v4i32, V1);
8039     int WidenedMask[4] = {
8040         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8041         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8042     return DAG.getBitcast(
8043         MVT::v2i64,
8044         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8045                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8046   }
8047   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8048   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8049   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8050   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8051
8052   // If we have a blend of two PACKUS operations an the blend aligns with the
8053   // low and half halves, we can just merge the PACKUS operations. This is
8054   // particularly important as it lets us merge shuffles that this routine itself
8055   // creates.
8056   auto GetPackNode = [](SDValue V) {
8057     while (V.getOpcode() == ISD::BITCAST)
8058       V = V.getOperand(0);
8059
8060     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8061   };
8062   if (SDValue V1Pack = GetPackNode(V1))
8063     if (SDValue V2Pack = GetPackNode(V2))
8064       return DAG.getBitcast(MVT::v2i64,
8065                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8066                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8067                                                      : V1Pack.getOperand(1),
8068                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8069                                                      : V2Pack.getOperand(1)));
8070
8071   // Try to use shift instructions.
8072   if (SDValue Shift =
8073           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8074     return Shift;
8075
8076   // When loading a scalar and then shuffling it into a vector we can often do
8077   // the insertion cheaply.
8078   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8079           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8080     return Insertion;
8081   // Try inverting the insertion since for v2 masks it is easy to do and we
8082   // can't reliably sort the mask one way or the other.
8083   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8084   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8085           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8086     return Insertion;
8087
8088   // We have different paths for blend lowering, but they all must use the
8089   // *exact* same predicate.
8090   bool IsBlendSupported = Subtarget->hasSSE41();
8091   if (IsBlendSupported)
8092     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8093                                                   Subtarget, DAG))
8094       return Blend;
8095
8096   // Use dedicated unpack instructions for masks that match their pattern.
8097   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8098     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8099   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8100     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8101
8102   // Try to use byte rotation instructions.
8103   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8104   if (Subtarget->hasSSSE3())
8105     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8106             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8107       return Rotate;
8108
8109   // If we have direct support for blends, we should lower by decomposing into
8110   // a permute. That will be faster than the domain cross.
8111   if (IsBlendSupported)
8112     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8113                                                       Mask, DAG);
8114
8115   // We implement this with SHUFPD which is pretty lame because it will likely
8116   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8117   // However, all the alternatives are still more cycles and newer chips don't
8118   // have this problem. It would be really nice if x86 had better shuffles here.
8119   V1 = DAG.getBitcast(MVT::v2f64, V1);
8120   V2 = DAG.getBitcast(MVT::v2f64, V2);
8121   return DAG.getBitcast(MVT::v2i64,
8122                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8123 }
8124
8125 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8126 ///
8127 /// This is used to disable more specialized lowerings when the shufps lowering
8128 /// will happen to be efficient.
8129 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8130   // This routine only handles 128-bit shufps.
8131   assert(Mask.size() == 4 && "Unsupported mask size!");
8132
8133   // To lower with a single SHUFPS we need to have the low half and high half
8134   // each requiring a single input.
8135   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8136     return false;
8137   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8138     return false;
8139
8140   return true;
8141 }
8142
8143 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8144 ///
8145 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8146 /// It makes no assumptions about whether this is the *best* lowering, it simply
8147 /// uses it.
8148 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8149                                             ArrayRef<int> Mask, SDValue V1,
8150                                             SDValue V2, SelectionDAG &DAG) {
8151   SDValue LowV = V1, HighV = V2;
8152   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8153
8154   int NumV2Elements =
8155       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8156
8157   if (NumV2Elements == 1) {
8158     int V2Index =
8159         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8160         Mask.begin();
8161
8162     // Compute the index adjacent to V2Index and in the same half by toggling
8163     // the low bit.
8164     int V2AdjIndex = V2Index ^ 1;
8165
8166     if (Mask[V2AdjIndex] == -1) {
8167       // Handles all the cases where we have a single V2 element and an undef.
8168       // This will only ever happen in the high lanes because we commute the
8169       // vector otherwise.
8170       if (V2Index < 2)
8171         std::swap(LowV, HighV);
8172       NewMask[V2Index] -= 4;
8173     } else {
8174       // Handle the case where the V2 element ends up adjacent to a V1 element.
8175       // To make this work, blend them together as the first step.
8176       int V1Index = V2AdjIndex;
8177       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8178       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8179                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8180
8181       // Now proceed to reconstruct the final blend as we have the necessary
8182       // high or low half formed.
8183       if (V2Index < 2) {
8184         LowV = V2;
8185         HighV = V1;
8186       } else {
8187         HighV = V2;
8188       }
8189       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8190       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8191     }
8192   } else if (NumV2Elements == 2) {
8193     if (Mask[0] < 4 && Mask[1] < 4) {
8194       // Handle the easy case where we have V1 in the low lanes and V2 in the
8195       // high lanes.
8196       NewMask[2] -= 4;
8197       NewMask[3] -= 4;
8198     } else if (Mask[2] < 4 && Mask[3] < 4) {
8199       // We also handle the reversed case because this utility may get called
8200       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8201       // arrange things in the right direction.
8202       NewMask[0] -= 4;
8203       NewMask[1] -= 4;
8204       HighV = V1;
8205       LowV = V2;
8206     } else {
8207       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8208       // trying to place elements directly, just blend them and set up the final
8209       // shuffle to place them.
8210
8211       // The first two blend mask elements are for V1, the second two are for
8212       // V2.
8213       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8214                           Mask[2] < 4 ? Mask[2] : Mask[3],
8215                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8216                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8217       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8218                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8219
8220       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8221       // a blend.
8222       LowV = HighV = V1;
8223       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8224       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8225       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8226       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8227     }
8228   }
8229   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8230                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8231 }
8232
8233 /// \brief Lower 4-lane 32-bit floating point shuffles.
8234 ///
8235 /// Uses instructions exclusively from the floating point unit to minimize
8236 /// domain crossing penalties, as these are sufficient to implement all v4f32
8237 /// shuffles.
8238 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8239                                        const X86Subtarget *Subtarget,
8240                                        SelectionDAG &DAG) {
8241   SDLoc DL(Op);
8242   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8243   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8244   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8245   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8246   ArrayRef<int> Mask = SVOp->getMask();
8247   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8248
8249   int NumV2Elements =
8250       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8251
8252   if (NumV2Elements == 0) {
8253     // Check for being able to broadcast a single element.
8254     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8255                                                           Mask, Subtarget, DAG))
8256       return Broadcast;
8257
8258     // Use even/odd duplicate instructions for masks that match their pattern.
8259     if (Subtarget->hasSSE3()) {
8260       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8261         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8262       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8263         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8264     }
8265
8266     if (Subtarget->hasAVX()) {
8267       // If we have AVX, we can use VPERMILPS which will allow folding a load
8268       // into the shuffle.
8269       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8270                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8271     }
8272
8273     // Otherwise, use a straight shuffle of a single input vector. We pass the
8274     // input vector to both operands to simulate this with a SHUFPS.
8275     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8276                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8277   }
8278
8279   // There are special ways we can lower some single-element blends. However, we
8280   // have custom ways we can lower more complex single-element blends below that
8281   // we defer to if both this and BLENDPS fail to match, so restrict this to
8282   // when the V2 input is targeting element 0 of the mask -- that is the fast
8283   // case here.
8284   if (NumV2Elements == 1 && Mask[0] >= 4)
8285     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8286                                                          Mask, Subtarget, DAG))
8287       return V;
8288
8289   if (Subtarget->hasSSE41()) {
8290     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8291                                                   Subtarget, DAG))
8292       return Blend;
8293
8294     // Use INSERTPS if we can complete the shuffle efficiently.
8295     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8296       return V;
8297
8298     if (!isSingleSHUFPSMask(Mask))
8299       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8300               DL, MVT::v4f32, V1, V2, Mask, DAG))
8301         return BlendPerm;
8302   }
8303
8304   // Use dedicated unpack instructions for masks that match their pattern.
8305   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8306     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8307   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8308     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8309   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8310     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8311   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8312     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8313
8314   // Otherwise fall back to a SHUFPS lowering strategy.
8315   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8316 }
8317
8318 /// \brief Lower 4-lane i32 vector shuffles.
8319 ///
8320 /// We try to handle these with integer-domain shuffles where we can, but for
8321 /// blends we use the floating point domain blend instructions.
8322 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8323                                        const X86Subtarget *Subtarget,
8324                                        SelectionDAG &DAG) {
8325   SDLoc DL(Op);
8326   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8327   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8328   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8329   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8330   ArrayRef<int> Mask = SVOp->getMask();
8331   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8332
8333   // Whenever we can lower this as a zext, that instruction is strictly faster
8334   // than any alternative. It also allows us to fold memory operands into the
8335   // shuffle in many cases.
8336   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8337                                                          Mask, Subtarget, DAG))
8338     return ZExt;
8339
8340   int NumV2Elements =
8341       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8342
8343   if (NumV2Elements == 0) {
8344     // Check for being able to broadcast a single element.
8345     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8346                                                           Mask, Subtarget, DAG))
8347       return Broadcast;
8348
8349     // Straight shuffle of a single input vector. For everything from SSE2
8350     // onward this has a single fast instruction with no scary immediates.
8351     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8352     // but we aren't actually going to use the UNPCK instruction because doing
8353     // so prevents folding a load into this instruction or making a copy.
8354     const int UnpackLoMask[] = {0, 0, 1, 1};
8355     const int UnpackHiMask[] = {2, 2, 3, 3};
8356     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8357       Mask = UnpackLoMask;
8358     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8359       Mask = UnpackHiMask;
8360
8361     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8362                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8363   }
8364
8365   // Try to use shift instructions.
8366   if (SDValue Shift =
8367           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8368     return Shift;
8369
8370   // There are special ways we can lower some single-element blends.
8371   if (NumV2Elements == 1)
8372     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8373                                                          Mask, Subtarget, DAG))
8374       return V;
8375
8376   // We have different paths for blend lowering, but they all must use the
8377   // *exact* same predicate.
8378   bool IsBlendSupported = Subtarget->hasSSE41();
8379   if (IsBlendSupported)
8380     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8381                                                   Subtarget, DAG))
8382       return Blend;
8383
8384   if (SDValue Masked =
8385           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8386     return Masked;
8387
8388   // Use dedicated unpack instructions for masks that match their pattern.
8389   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8390     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8391   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8392     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8393   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8394     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8395   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8396     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8397
8398   // Try to use byte rotation instructions.
8399   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8400   if (Subtarget->hasSSSE3())
8401     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8402             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8403       return Rotate;
8404
8405   // If we have direct support for blends, we should lower by decomposing into
8406   // a permute. That will be faster than the domain cross.
8407   if (IsBlendSupported)
8408     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8409                                                       Mask, DAG);
8410
8411   // Try to lower by permuting the inputs into an unpack instruction.
8412   if (SDValue Unpack =
8413           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8414     return Unpack;
8415
8416   // We implement this with SHUFPS because it can blend from two vectors.
8417   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8418   // up the inputs, bypassing domain shift penalties that we would encur if we
8419   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8420   // relevant.
8421   return DAG.getBitcast(
8422       MVT::v4i32,
8423       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8424                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8425 }
8426
8427 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8428 /// shuffle lowering, and the most complex part.
8429 ///
8430 /// The lowering strategy is to try to form pairs of input lanes which are
8431 /// targeted at the same half of the final vector, and then use a dword shuffle
8432 /// to place them onto the right half, and finally unpack the paired lanes into
8433 /// their final position.
8434 ///
8435 /// The exact breakdown of how to form these dword pairs and align them on the
8436 /// correct sides is really tricky. See the comments within the function for
8437 /// more of the details.
8438 ///
8439 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8440 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8441 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8442 /// vector, form the analogous 128-bit 8-element Mask.
8443 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8444     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8445     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8446   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8447   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8448
8449   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8450   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8451   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8452
8453   SmallVector<int, 4> LoInputs;
8454   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8455                [](int M) { return M >= 0; });
8456   std::sort(LoInputs.begin(), LoInputs.end());
8457   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8458   SmallVector<int, 4> HiInputs;
8459   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8460                [](int M) { return M >= 0; });
8461   std::sort(HiInputs.begin(), HiInputs.end());
8462   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8463   int NumLToL =
8464       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8465   int NumHToL = LoInputs.size() - NumLToL;
8466   int NumLToH =
8467       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8468   int NumHToH = HiInputs.size() - NumLToH;
8469   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8470   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8471   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8472   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8473
8474   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8475   // such inputs we can swap two of the dwords across the half mark and end up
8476   // with <=2 inputs to each half in each half. Once there, we can fall through
8477   // to the generic code below. For example:
8478   //
8479   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8480   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8481   //
8482   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8483   // and an existing 2-into-2 on the other half. In this case we may have to
8484   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8485   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8486   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8487   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8488   // half than the one we target for fixing) will be fixed when we re-enter this
8489   // path. We will also combine away any sequence of PSHUFD instructions that
8490   // result into a single instruction. Here is an example of the tricky case:
8491   //
8492   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8493   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8494   //
8495   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8496   //
8497   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8498   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8499   //
8500   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8501   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8502   //
8503   // The result is fine to be handled by the generic logic.
8504   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8505                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8506                           int AOffset, int BOffset) {
8507     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8508            "Must call this with A having 3 or 1 inputs from the A half.");
8509     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8510            "Must call this with B having 1 or 3 inputs from the B half.");
8511     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8512            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8513
8514     bool ThreeAInputs = AToAInputs.size() == 3;
8515
8516     // Compute the index of dword with only one word among the three inputs in
8517     // a half by taking the sum of the half with three inputs and subtracting
8518     // the sum of the actual three inputs. The difference is the remaining
8519     // slot.
8520     int ADWord, BDWord;
8521     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8522     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8523     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8524     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8525     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8526     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8527     int TripleNonInputIdx =
8528         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8529     TripleDWord = TripleNonInputIdx / 2;
8530
8531     // We use xor with one to compute the adjacent DWord to whichever one the
8532     // OneInput is in.
8533     OneInputDWord = (OneInput / 2) ^ 1;
8534
8535     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8536     // and BToA inputs. If there is also such a problem with the BToB and AToB
8537     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8538     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8539     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8540     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8541       // Compute how many inputs will be flipped by swapping these DWords. We
8542       // need
8543       // to balance this to ensure we don't form a 3-1 shuffle in the other
8544       // half.
8545       int NumFlippedAToBInputs =
8546           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8547           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8548       int NumFlippedBToBInputs =
8549           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8550           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8551       if ((NumFlippedAToBInputs == 1 &&
8552            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8553           (NumFlippedBToBInputs == 1 &&
8554            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8555         // We choose whether to fix the A half or B half based on whether that
8556         // half has zero flipped inputs. At zero, we may not be able to fix it
8557         // with that half. We also bias towards fixing the B half because that
8558         // will more commonly be the high half, and we have to bias one way.
8559         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8560                                                        ArrayRef<int> Inputs) {
8561           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8562           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8563                                          PinnedIdx ^ 1) != Inputs.end();
8564           // Determine whether the free index is in the flipped dword or the
8565           // unflipped dword based on where the pinned index is. We use this bit
8566           // in an xor to conditionally select the adjacent dword.
8567           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8568           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8569                                              FixFreeIdx) != Inputs.end();
8570           if (IsFixIdxInput == IsFixFreeIdxInput)
8571             FixFreeIdx += 1;
8572           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8573                                         FixFreeIdx) != Inputs.end();
8574           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8575                  "We need to be changing the number of flipped inputs!");
8576           int PSHUFHalfMask[] = {0, 1, 2, 3};
8577           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8578           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8579                           MVT::v8i16, V,
8580                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8581
8582           for (int &M : Mask)
8583             if (M != -1 && M == FixIdx)
8584               M = FixFreeIdx;
8585             else if (M != -1 && M == FixFreeIdx)
8586               M = FixIdx;
8587         };
8588         if (NumFlippedBToBInputs != 0) {
8589           int BPinnedIdx =
8590               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8591           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8592         } else {
8593           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8594           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8595           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8596         }
8597       }
8598     }
8599
8600     int PSHUFDMask[] = {0, 1, 2, 3};
8601     PSHUFDMask[ADWord] = BDWord;
8602     PSHUFDMask[BDWord] = ADWord;
8603     V = DAG.getBitcast(
8604         VT,
8605         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8606                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8607
8608     // Adjust the mask to match the new locations of A and B.
8609     for (int &M : Mask)
8610       if (M != -1 && M/2 == ADWord)
8611         M = 2 * BDWord + M % 2;
8612       else if (M != -1 && M/2 == BDWord)
8613         M = 2 * ADWord + M % 2;
8614
8615     // Recurse back into this routine to re-compute state now that this isn't
8616     // a 3 and 1 problem.
8617     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8618                                                      DAG);
8619   };
8620   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8621     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8622   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8623     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8624
8625   // At this point there are at most two inputs to the low and high halves from
8626   // each half. That means the inputs can always be grouped into dwords and
8627   // those dwords can then be moved to the correct half with a dword shuffle.
8628   // We use at most one low and one high word shuffle to collect these paired
8629   // inputs into dwords, and finally a dword shuffle to place them.
8630   int PSHUFLMask[4] = {-1, -1, -1, -1};
8631   int PSHUFHMask[4] = {-1, -1, -1, -1};
8632   int PSHUFDMask[4] = {-1, -1, -1, -1};
8633
8634   // First fix the masks for all the inputs that are staying in their
8635   // original halves. This will then dictate the targets of the cross-half
8636   // shuffles.
8637   auto fixInPlaceInputs =
8638       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8639                     MutableArrayRef<int> SourceHalfMask,
8640                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8641     if (InPlaceInputs.empty())
8642       return;
8643     if (InPlaceInputs.size() == 1) {
8644       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8645           InPlaceInputs[0] - HalfOffset;
8646       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8647       return;
8648     }
8649     if (IncomingInputs.empty()) {
8650       // Just fix all of the in place inputs.
8651       for (int Input : InPlaceInputs) {
8652         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8653         PSHUFDMask[Input / 2] = Input / 2;
8654       }
8655       return;
8656     }
8657
8658     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8659     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8660         InPlaceInputs[0] - HalfOffset;
8661     // Put the second input next to the first so that they are packed into
8662     // a dword. We find the adjacent index by toggling the low bit.
8663     int AdjIndex = InPlaceInputs[0] ^ 1;
8664     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8665     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8666     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8667   };
8668   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8669   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8670
8671   // Now gather the cross-half inputs and place them into a free dword of
8672   // their target half.
8673   // FIXME: This operation could almost certainly be simplified dramatically to
8674   // look more like the 3-1 fixing operation.
8675   auto moveInputsToRightHalf = [&PSHUFDMask](
8676       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8677       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8678       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8679       int DestOffset) {
8680     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8681       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8682     };
8683     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8684                                                int Word) {
8685       int LowWord = Word & ~1;
8686       int HighWord = Word | 1;
8687       return isWordClobbered(SourceHalfMask, LowWord) ||
8688              isWordClobbered(SourceHalfMask, HighWord);
8689     };
8690
8691     if (IncomingInputs.empty())
8692       return;
8693
8694     if (ExistingInputs.empty()) {
8695       // Map any dwords with inputs from them into the right half.
8696       for (int Input : IncomingInputs) {
8697         // If the source half mask maps over the inputs, turn those into
8698         // swaps and use the swapped lane.
8699         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8700           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8701             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8702                 Input - SourceOffset;
8703             // We have to swap the uses in our half mask in one sweep.
8704             for (int &M : HalfMask)
8705               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8706                 M = Input;
8707               else if (M == Input)
8708                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8709           } else {
8710             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8711                        Input - SourceOffset &&
8712                    "Previous placement doesn't match!");
8713           }
8714           // Note that this correctly re-maps both when we do a swap and when
8715           // we observe the other side of the swap above. We rely on that to
8716           // avoid swapping the members of the input list directly.
8717           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8718         }
8719
8720         // Map the input's dword into the correct half.
8721         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8722           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8723         else
8724           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8725                      Input / 2 &&
8726                  "Previous placement doesn't match!");
8727       }
8728
8729       // And just directly shift any other-half mask elements to be same-half
8730       // as we will have mirrored the dword containing the element into the
8731       // same position within that half.
8732       for (int &M : HalfMask)
8733         if (M >= SourceOffset && M < SourceOffset + 4) {
8734           M = M - SourceOffset + DestOffset;
8735           assert(M >= 0 && "This should never wrap below zero!");
8736         }
8737       return;
8738     }
8739
8740     // Ensure we have the input in a viable dword of its current half. This
8741     // is particularly tricky because the original position may be clobbered
8742     // by inputs being moved and *staying* in that half.
8743     if (IncomingInputs.size() == 1) {
8744       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8745         int InputFixed = std::find(std::begin(SourceHalfMask),
8746                                    std::end(SourceHalfMask), -1) -
8747                          std::begin(SourceHalfMask) + SourceOffset;
8748         SourceHalfMask[InputFixed - SourceOffset] =
8749             IncomingInputs[0] - SourceOffset;
8750         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8751                      InputFixed);
8752         IncomingInputs[0] = InputFixed;
8753       }
8754     } else if (IncomingInputs.size() == 2) {
8755       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8756           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8757         // We have two non-adjacent or clobbered inputs we need to extract from
8758         // the source half. To do this, we need to map them into some adjacent
8759         // dword slot in the source mask.
8760         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8761                               IncomingInputs[1] - SourceOffset};
8762
8763         // If there is a free slot in the source half mask adjacent to one of
8764         // the inputs, place the other input in it. We use (Index XOR 1) to
8765         // compute an adjacent index.
8766         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8767             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8768           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8769           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8770           InputsFixed[1] = InputsFixed[0] ^ 1;
8771         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8772                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8773           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8774           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8775           InputsFixed[0] = InputsFixed[1] ^ 1;
8776         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8777                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8778           // The two inputs are in the same DWord but it is clobbered and the
8779           // adjacent DWord isn't used at all. Move both inputs to the free
8780           // slot.
8781           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8782           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8783           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8784           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8785         } else {
8786           // The only way we hit this point is if there is no clobbering
8787           // (because there are no off-half inputs to this half) and there is no
8788           // free slot adjacent to one of the inputs. In this case, we have to
8789           // swap an input with a non-input.
8790           for (int i = 0; i < 4; ++i)
8791             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8792                    "We can't handle any clobbers here!");
8793           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8794                  "Cannot have adjacent inputs here!");
8795
8796           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8797           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8798
8799           // We also have to update the final source mask in this case because
8800           // it may need to undo the above swap.
8801           for (int &M : FinalSourceHalfMask)
8802             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8803               M = InputsFixed[1] + SourceOffset;
8804             else if (M == InputsFixed[1] + SourceOffset)
8805               M = (InputsFixed[0] ^ 1) + SourceOffset;
8806
8807           InputsFixed[1] = InputsFixed[0] ^ 1;
8808         }
8809
8810         // Point everything at the fixed inputs.
8811         for (int &M : HalfMask)
8812           if (M == IncomingInputs[0])
8813             M = InputsFixed[0] + SourceOffset;
8814           else if (M == IncomingInputs[1])
8815             M = InputsFixed[1] + SourceOffset;
8816
8817         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8818         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8819       }
8820     } else {
8821       llvm_unreachable("Unhandled input size!");
8822     }
8823
8824     // Now hoist the DWord down to the right half.
8825     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8826     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8827     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8828     for (int &M : HalfMask)
8829       for (int Input : IncomingInputs)
8830         if (M == Input)
8831           M = FreeDWord * 2 + Input % 2;
8832   };
8833   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8834                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8835   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8836                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8837
8838   // Now enact all the shuffles we've computed to move the inputs into their
8839   // target half.
8840   if (!isNoopShuffleMask(PSHUFLMask))
8841     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8842                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8843   if (!isNoopShuffleMask(PSHUFHMask))
8844     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8845                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8846   if (!isNoopShuffleMask(PSHUFDMask))
8847     V = DAG.getBitcast(
8848         VT,
8849         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8850                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8851
8852   // At this point, each half should contain all its inputs, and we can then
8853   // just shuffle them into their final position.
8854   assert(std::count_if(LoMask.begin(), LoMask.end(),
8855                        [](int M) { return M >= 4; }) == 0 &&
8856          "Failed to lift all the high half inputs to the low mask!");
8857   assert(std::count_if(HiMask.begin(), HiMask.end(),
8858                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8859          "Failed to lift all the low half inputs to the high mask!");
8860
8861   // Do a half shuffle for the low mask.
8862   if (!isNoopShuffleMask(LoMask))
8863     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8864                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8865
8866   // Do a half shuffle with the high mask after shifting its values down.
8867   for (int &M : HiMask)
8868     if (M >= 0)
8869       M -= 4;
8870   if (!isNoopShuffleMask(HiMask))
8871     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8872                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8873
8874   return V;
8875 }
8876
8877 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8878 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8879                                           SDValue V2, ArrayRef<int> Mask,
8880                                           SelectionDAG &DAG, bool &V1InUse,
8881                                           bool &V2InUse) {
8882   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8883   SDValue V1Mask[16];
8884   SDValue V2Mask[16];
8885   V1InUse = false;
8886   V2InUse = false;
8887
8888   int Size = Mask.size();
8889   int Scale = 16 / Size;
8890   for (int i = 0; i < 16; ++i) {
8891     if (Mask[i / Scale] == -1) {
8892       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8893     } else {
8894       const int ZeroMask = 0x80;
8895       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8896                                           : ZeroMask;
8897       int V2Idx = Mask[i / Scale] < Size
8898                       ? ZeroMask
8899                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8900       if (Zeroable[i / Scale])
8901         V1Idx = V2Idx = ZeroMask;
8902       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8903       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8904       V1InUse |= (ZeroMask != V1Idx);
8905       V2InUse |= (ZeroMask != V2Idx);
8906     }
8907   }
8908
8909   if (V1InUse)
8910     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8911                      DAG.getBitcast(MVT::v16i8, V1),
8912                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8913   if (V2InUse)
8914     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8915                      DAG.getBitcast(MVT::v16i8, V2),
8916                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8917
8918   // If we need shuffled inputs from both, blend the two.
8919   SDValue V;
8920   if (V1InUse && V2InUse)
8921     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8922   else
8923     V = V1InUse ? V1 : V2;
8924
8925   // Cast the result back to the correct type.
8926   return DAG.getBitcast(VT, V);
8927 }
8928
8929 /// \brief Generic lowering of 8-lane i16 shuffles.
8930 ///
8931 /// This handles both single-input shuffles and combined shuffle/blends with
8932 /// two inputs. The single input shuffles are immediately delegated to
8933 /// a dedicated lowering routine.
8934 ///
8935 /// The blends are lowered in one of three fundamental ways. If there are few
8936 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8937 /// of the input is significantly cheaper when lowered as an interleaving of
8938 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8939 /// halves of the inputs separately (making them have relatively few inputs)
8940 /// and then concatenate them.
8941 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8942                                        const X86Subtarget *Subtarget,
8943                                        SelectionDAG &DAG) {
8944   SDLoc DL(Op);
8945   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8946   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8947   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8948   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8949   ArrayRef<int> OrigMask = SVOp->getMask();
8950   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8951                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8952   MutableArrayRef<int> Mask(MaskStorage);
8953
8954   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8955
8956   // Whenever we can lower this as a zext, that instruction is strictly faster
8957   // than any alternative.
8958   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8959           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8960     return ZExt;
8961
8962   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8963   (void)isV1;
8964   auto isV2 = [](int M) { return M >= 8; };
8965
8966   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8967
8968   if (NumV2Inputs == 0) {
8969     // Check for being able to broadcast a single element.
8970     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8971                                                           Mask, Subtarget, DAG))
8972       return Broadcast;
8973
8974     // Try to use shift instructions.
8975     if (SDValue Shift =
8976             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8977       return Shift;
8978
8979     // Use dedicated unpack instructions for masks that match their pattern.
8980     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8981       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8982     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8983       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8984
8985     // Try to use byte rotation instructions.
8986     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8987                                                         Mask, Subtarget, DAG))
8988       return Rotate;
8989
8990     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8991                                                      Subtarget, DAG);
8992   }
8993
8994   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8995          "All single-input shuffles should be canonicalized to be V1-input "
8996          "shuffles.");
8997
8998   // Try to use shift instructions.
8999   if (SDValue Shift =
9000           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9001     return Shift;
9002
9003   // See if we can use SSE4A Extraction / Insertion.
9004   if (Subtarget->hasSSE4A())
9005     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9006       return V;
9007
9008   // There are special ways we can lower some single-element blends.
9009   if (NumV2Inputs == 1)
9010     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9011                                                          Mask, Subtarget, DAG))
9012       return V;
9013
9014   // We have different paths for blend lowering, but they all must use the
9015   // *exact* same predicate.
9016   bool IsBlendSupported = Subtarget->hasSSE41();
9017   if (IsBlendSupported)
9018     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9019                                                   Subtarget, DAG))
9020       return Blend;
9021
9022   if (SDValue Masked =
9023           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9024     return Masked;
9025
9026   // Use dedicated unpack instructions for masks that match their pattern.
9027   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9028     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9029   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9030     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9031
9032   // Try to use byte rotation instructions.
9033   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9034           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9035     return Rotate;
9036
9037   if (SDValue BitBlend =
9038           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9039     return BitBlend;
9040
9041   if (SDValue Unpack =
9042           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
9043     return Unpack;
9044
9045   // If we can't directly blend but can use PSHUFB, that will be better as it
9046   // can both shuffle and set up the inefficient blend.
9047   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9048     bool V1InUse, V2InUse;
9049     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9050                                       V1InUse, V2InUse);
9051   }
9052
9053   // We can always bit-blend if we have to so the fallback strategy is to
9054   // decompose into single-input permutes and blends.
9055   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9056                                                       Mask, DAG);
9057 }
9058
9059 /// \brief Check whether a compaction lowering can be done by dropping even
9060 /// elements and compute how many times even elements must be dropped.
9061 ///
9062 /// This handles shuffles which take every Nth element where N is a power of
9063 /// two. Example shuffle masks:
9064 ///
9065 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9066 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9067 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9068 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9069 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9070 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9071 ///
9072 /// Any of these lanes can of course be undef.
9073 ///
9074 /// This routine only supports N <= 3.
9075 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9076 /// for larger N.
9077 ///
9078 /// \returns N above, or the number of times even elements must be dropped if
9079 /// there is such a number. Otherwise returns zero.
9080 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9081   // Figure out whether we're looping over two inputs or just one.
9082   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9083
9084   // The modulus for the shuffle vector entries is based on whether this is
9085   // a single input or not.
9086   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9087   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9088          "We should only be called with masks with a power-of-2 size!");
9089
9090   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9091
9092   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9093   // and 2^3 simultaneously. This is because we may have ambiguity with
9094   // partially undef inputs.
9095   bool ViableForN[3] = {true, true, true};
9096
9097   for (int i = 0, e = Mask.size(); i < e; ++i) {
9098     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9099     // want.
9100     if (Mask[i] == -1)
9101       continue;
9102
9103     bool IsAnyViable = false;
9104     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9105       if (ViableForN[j]) {
9106         uint64_t N = j + 1;
9107
9108         // The shuffle mask must be equal to (i * 2^N) % M.
9109         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9110           IsAnyViable = true;
9111         else
9112           ViableForN[j] = false;
9113       }
9114     // Early exit if we exhaust the possible powers of two.
9115     if (!IsAnyViable)
9116       break;
9117   }
9118
9119   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9120     if (ViableForN[j])
9121       return j + 1;
9122
9123   // Return 0 as there is no viable power of two.
9124   return 0;
9125 }
9126
9127 /// \brief Generic lowering of v16i8 shuffles.
9128 ///
9129 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9130 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9131 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9132 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9133 /// back together.
9134 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9135                                        const X86Subtarget *Subtarget,
9136                                        SelectionDAG &DAG) {
9137   SDLoc DL(Op);
9138   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9139   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9140   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9141   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9142   ArrayRef<int> Mask = SVOp->getMask();
9143   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9144
9145   // Try to use shift instructions.
9146   if (SDValue Shift =
9147           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9148     return Shift;
9149
9150   // Try to use byte rotation instructions.
9151   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9152           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9153     return Rotate;
9154
9155   // Try to use a zext lowering.
9156   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9157           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9158     return ZExt;
9159
9160   // See if we can use SSE4A Extraction / Insertion.
9161   if (Subtarget->hasSSE4A())
9162     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9163       return V;
9164
9165   int NumV2Elements =
9166       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9167
9168   // For single-input shuffles, there are some nicer lowering tricks we can use.
9169   if (NumV2Elements == 0) {
9170     // Check for being able to broadcast a single element.
9171     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9172                                                           Mask, Subtarget, DAG))
9173       return Broadcast;
9174
9175     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9176     // Notably, this handles splat and partial-splat shuffles more efficiently.
9177     // However, it only makes sense if the pre-duplication shuffle simplifies
9178     // things significantly. Currently, this means we need to be able to
9179     // express the pre-duplication shuffle as an i16 shuffle.
9180     //
9181     // FIXME: We should check for other patterns which can be widened into an
9182     // i16 shuffle as well.
9183     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9184       for (int i = 0; i < 16; i += 2)
9185         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9186           return false;
9187
9188       return true;
9189     };
9190     auto tryToWidenViaDuplication = [&]() -> SDValue {
9191       if (!canWidenViaDuplication(Mask))
9192         return SDValue();
9193       SmallVector<int, 4> LoInputs;
9194       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9195                    [](int M) { return M >= 0 && M < 8; });
9196       std::sort(LoInputs.begin(), LoInputs.end());
9197       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9198                      LoInputs.end());
9199       SmallVector<int, 4> HiInputs;
9200       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9201                    [](int M) { return M >= 8; });
9202       std::sort(HiInputs.begin(), HiInputs.end());
9203       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9204                      HiInputs.end());
9205
9206       bool TargetLo = LoInputs.size() >= HiInputs.size();
9207       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9208       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9209
9210       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9211       SmallDenseMap<int, int, 8> LaneMap;
9212       for (int I : InPlaceInputs) {
9213         PreDupI16Shuffle[I/2] = I/2;
9214         LaneMap[I] = I;
9215       }
9216       int j = TargetLo ? 0 : 4, je = j + 4;
9217       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9218         // Check if j is already a shuffle of this input. This happens when
9219         // there are two adjacent bytes after we move the low one.
9220         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9221           // If we haven't yet mapped the input, search for a slot into which
9222           // we can map it.
9223           while (j < je && PreDupI16Shuffle[j] != -1)
9224             ++j;
9225
9226           if (j == je)
9227             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9228             return SDValue();
9229
9230           // Map this input with the i16 shuffle.
9231           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9232         }
9233
9234         // Update the lane map based on the mapping we ended up with.
9235         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9236       }
9237       V1 = DAG.getBitcast(
9238           MVT::v16i8,
9239           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9240                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9241
9242       // Unpack the bytes to form the i16s that will be shuffled into place.
9243       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9244                        MVT::v16i8, V1, V1);
9245
9246       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9247       for (int i = 0; i < 16; ++i)
9248         if (Mask[i] != -1) {
9249           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9250           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9251           if (PostDupI16Shuffle[i / 2] == -1)
9252             PostDupI16Shuffle[i / 2] = MappedMask;
9253           else
9254             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9255                    "Conflicting entrties in the original shuffle!");
9256         }
9257       return DAG.getBitcast(
9258           MVT::v16i8,
9259           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9260                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9261     };
9262     if (SDValue V = tryToWidenViaDuplication())
9263       return V;
9264   }
9265
9266   if (SDValue Masked =
9267           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9268     return Masked;
9269
9270   // Use dedicated unpack instructions for masks that match their pattern.
9271   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9272                                          0, 16, 1, 17, 2, 18, 3, 19,
9273                                          // High half.
9274                                          4, 20, 5, 21, 6, 22, 7, 23}))
9275     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9276   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9277                                          8, 24, 9, 25, 10, 26, 11, 27,
9278                                          // High half.
9279                                          12, 28, 13, 29, 14, 30, 15, 31}))
9280     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9281
9282   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9283   // with PSHUFB. It is important to do this before we attempt to generate any
9284   // blends but after all of the single-input lowerings. If the single input
9285   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9286   // want to preserve that and we can DAG combine any longer sequences into
9287   // a PSHUFB in the end. But once we start blending from multiple inputs,
9288   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9289   // and there are *very* few patterns that would actually be faster than the
9290   // PSHUFB approach because of its ability to zero lanes.
9291   //
9292   // FIXME: The only exceptions to the above are blends which are exact
9293   // interleavings with direct instructions supporting them. We currently don't
9294   // handle those well here.
9295   if (Subtarget->hasSSSE3()) {
9296     bool V1InUse = false;
9297     bool V2InUse = false;
9298
9299     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9300                                                 DAG, V1InUse, V2InUse);
9301
9302     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9303     // do so. This avoids using them to handle blends-with-zero which is
9304     // important as a single pshufb is significantly faster for that.
9305     if (V1InUse && V2InUse) {
9306       if (Subtarget->hasSSE41())
9307         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9308                                                       Mask, Subtarget, DAG))
9309           return Blend;
9310
9311       // We can use an unpack to do the blending rather than an or in some
9312       // cases. Even though the or may be (very minorly) more efficient, we
9313       // preference this lowering because there are common cases where part of
9314       // the complexity of the shuffles goes away when we do the final blend as
9315       // an unpack.
9316       // FIXME: It might be worth trying to detect if the unpack-feeding
9317       // shuffles will both be pshufb, in which case we shouldn't bother with
9318       // this.
9319       if (SDValue Unpack =
9320               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9321         return Unpack;
9322     }
9323
9324     return PSHUFB;
9325   }
9326
9327   // There are special ways we can lower some single-element blends.
9328   if (NumV2Elements == 1)
9329     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9330                                                          Mask, Subtarget, DAG))
9331       return V;
9332
9333   if (SDValue BitBlend =
9334           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9335     return BitBlend;
9336
9337   // Check whether a compaction lowering can be done. This handles shuffles
9338   // which take every Nth element for some even N. See the helper function for
9339   // details.
9340   //
9341   // We special case these as they can be particularly efficiently handled with
9342   // the PACKUSB instruction on x86 and they show up in common patterns of
9343   // rearranging bytes to truncate wide elements.
9344   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9345     // NumEvenDrops is the power of two stride of the elements. Another way of
9346     // thinking about it is that we need to drop the even elements this many
9347     // times to get the original input.
9348     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9349
9350     // First we need to zero all the dropped bytes.
9351     assert(NumEvenDrops <= 3 &&
9352            "No support for dropping even elements more than 3 times.");
9353     // We use the mask type to pick which bytes are preserved based on how many
9354     // elements are dropped.
9355     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9356     SDValue ByteClearMask = DAG.getBitcast(
9357         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9358     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9359     if (!IsSingleInput)
9360       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9361
9362     // Now pack things back together.
9363     V1 = DAG.getBitcast(MVT::v8i16, V1);
9364     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9365     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9366     for (int i = 1; i < NumEvenDrops; ++i) {
9367       Result = DAG.getBitcast(MVT::v8i16, Result);
9368       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9369     }
9370
9371     return Result;
9372   }
9373
9374   // Handle multi-input cases by blending single-input shuffles.
9375   if (NumV2Elements > 0)
9376     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9377                                                       Mask, DAG);
9378
9379   // The fallback path for single-input shuffles widens this into two v8i16
9380   // vectors with unpacks, shuffles those, and then pulls them back together
9381   // with a pack.
9382   SDValue V = V1;
9383
9384   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9385   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9386   for (int i = 0; i < 16; ++i)
9387     if (Mask[i] >= 0)
9388       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9389
9390   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9391
9392   SDValue VLoHalf, VHiHalf;
9393   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9394   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9395   // i16s.
9396   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9397                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9398       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9399                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9400     // Use a mask to drop the high bytes.
9401     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9402     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9403                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9404
9405     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9406     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9407
9408     // Squash the masks to point directly into VLoHalf.
9409     for (int &M : LoBlendMask)
9410       if (M >= 0)
9411         M /= 2;
9412     for (int &M : HiBlendMask)
9413       if (M >= 0)
9414         M /= 2;
9415   } else {
9416     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9417     // VHiHalf so that we can blend them as i16s.
9418     VLoHalf = DAG.getBitcast(
9419         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9420     VHiHalf = DAG.getBitcast(
9421         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9422   }
9423
9424   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9425   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9426
9427   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9428 }
9429
9430 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9431 ///
9432 /// This routine breaks down the specific type of 128-bit shuffle and
9433 /// dispatches to the lowering routines accordingly.
9434 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9435                                         MVT VT, const X86Subtarget *Subtarget,
9436                                         SelectionDAG &DAG) {
9437   switch (VT.SimpleTy) {
9438   case MVT::v2i64:
9439     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9440   case MVT::v2f64:
9441     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9442   case MVT::v4i32:
9443     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9444   case MVT::v4f32:
9445     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9446   case MVT::v8i16:
9447     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9448   case MVT::v16i8:
9449     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9450
9451   default:
9452     llvm_unreachable("Unimplemented!");
9453   }
9454 }
9455
9456 /// \brief Helper function to test whether a shuffle mask could be
9457 /// simplified by widening the elements being shuffled.
9458 ///
9459 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9460 /// leaves it in an unspecified state.
9461 ///
9462 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9463 /// shuffle masks. The latter have the special property of a '-2' representing
9464 /// a zero-ed lane of a vector.
9465 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9466                                     SmallVectorImpl<int> &WidenedMask) {
9467   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9468     // If both elements are undef, its trivial.
9469     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9470       WidenedMask.push_back(SM_SentinelUndef);
9471       continue;
9472     }
9473
9474     // Check for an undef mask and a mask value properly aligned to fit with
9475     // a pair of values. If we find such a case, use the non-undef mask's value.
9476     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9477       WidenedMask.push_back(Mask[i + 1] / 2);
9478       continue;
9479     }
9480     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9481       WidenedMask.push_back(Mask[i] / 2);
9482       continue;
9483     }
9484
9485     // When zeroing, we need to spread the zeroing across both lanes to widen.
9486     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9487       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9488           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9489         WidenedMask.push_back(SM_SentinelZero);
9490         continue;
9491       }
9492       return false;
9493     }
9494
9495     // Finally check if the two mask values are adjacent and aligned with
9496     // a pair.
9497     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9498       WidenedMask.push_back(Mask[i] / 2);
9499       continue;
9500     }
9501
9502     // Otherwise we can't safely widen the elements used in this shuffle.
9503     return false;
9504   }
9505   assert(WidenedMask.size() == Mask.size() / 2 &&
9506          "Incorrect size of mask after widening the elements!");
9507
9508   return true;
9509 }
9510
9511 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9512 ///
9513 /// This routine just extracts two subvectors, shuffles them independently, and
9514 /// then concatenates them back together. This should work effectively with all
9515 /// AVX vector shuffle types.
9516 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9517                                           SDValue V2, ArrayRef<int> Mask,
9518                                           SelectionDAG &DAG) {
9519   assert(VT.getSizeInBits() >= 256 &&
9520          "Only for 256-bit or wider vector shuffles!");
9521   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9522   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9523
9524   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9525   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9526
9527   int NumElements = VT.getVectorNumElements();
9528   int SplitNumElements = NumElements / 2;
9529   MVT ScalarVT = VT.getScalarType();
9530   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9531
9532   // Rather than splitting build-vectors, just build two narrower build
9533   // vectors. This helps shuffling with splats and zeros.
9534   auto SplitVector = [&](SDValue V) {
9535     while (V.getOpcode() == ISD::BITCAST)
9536       V = V->getOperand(0);
9537
9538     MVT OrigVT = V.getSimpleValueType();
9539     int OrigNumElements = OrigVT.getVectorNumElements();
9540     int OrigSplitNumElements = OrigNumElements / 2;
9541     MVT OrigScalarVT = OrigVT.getScalarType();
9542     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9543
9544     SDValue LoV, HiV;
9545
9546     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9547     if (!BV) {
9548       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9549                         DAG.getIntPtrConstant(0, DL));
9550       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9551                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9552     } else {
9553
9554       SmallVector<SDValue, 16> LoOps, HiOps;
9555       for (int i = 0; i < OrigSplitNumElements; ++i) {
9556         LoOps.push_back(BV->getOperand(i));
9557         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9558       }
9559       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9560       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9561     }
9562     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9563                           DAG.getBitcast(SplitVT, HiV));
9564   };
9565
9566   SDValue LoV1, HiV1, LoV2, HiV2;
9567   std::tie(LoV1, HiV1) = SplitVector(V1);
9568   std::tie(LoV2, HiV2) = SplitVector(V2);
9569
9570   // Now create two 4-way blends of these half-width vectors.
9571   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9572     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9573     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9574     for (int i = 0; i < SplitNumElements; ++i) {
9575       int M = HalfMask[i];
9576       if (M >= NumElements) {
9577         if (M >= NumElements + SplitNumElements)
9578           UseHiV2 = true;
9579         else
9580           UseLoV2 = true;
9581         V2BlendMask.push_back(M - NumElements);
9582         V1BlendMask.push_back(-1);
9583         BlendMask.push_back(SplitNumElements + i);
9584       } else if (M >= 0) {
9585         if (M >= SplitNumElements)
9586           UseHiV1 = true;
9587         else
9588           UseLoV1 = true;
9589         V2BlendMask.push_back(-1);
9590         V1BlendMask.push_back(M);
9591         BlendMask.push_back(i);
9592       } else {
9593         V2BlendMask.push_back(-1);
9594         V1BlendMask.push_back(-1);
9595         BlendMask.push_back(-1);
9596       }
9597     }
9598
9599     // Because the lowering happens after all combining takes place, we need to
9600     // manually combine these blend masks as much as possible so that we create
9601     // a minimal number of high-level vector shuffle nodes.
9602
9603     // First try just blending the halves of V1 or V2.
9604     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9605       return DAG.getUNDEF(SplitVT);
9606     if (!UseLoV2 && !UseHiV2)
9607       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9608     if (!UseLoV1 && !UseHiV1)
9609       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9610
9611     SDValue V1Blend, V2Blend;
9612     if (UseLoV1 && UseHiV1) {
9613       V1Blend =
9614         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9615     } else {
9616       // We only use half of V1 so map the usage down into the final blend mask.
9617       V1Blend = UseLoV1 ? LoV1 : HiV1;
9618       for (int i = 0; i < SplitNumElements; ++i)
9619         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9620           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9621     }
9622     if (UseLoV2 && UseHiV2) {
9623       V2Blend =
9624         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9625     } else {
9626       // We only use half of V2 so map the usage down into the final blend mask.
9627       V2Blend = UseLoV2 ? LoV2 : HiV2;
9628       for (int i = 0; i < SplitNumElements; ++i)
9629         if (BlendMask[i] >= SplitNumElements)
9630           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9631     }
9632     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9633   };
9634   SDValue Lo = HalfBlend(LoMask);
9635   SDValue Hi = HalfBlend(HiMask);
9636   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9637 }
9638
9639 /// \brief Either split a vector in halves or decompose the shuffles and the
9640 /// blend.
9641 ///
9642 /// This is provided as a good fallback for many lowerings of non-single-input
9643 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9644 /// between splitting the shuffle into 128-bit components and stitching those
9645 /// back together vs. extracting the single-input shuffles and blending those
9646 /// results.
9647 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9648                                                 SDValue V2, ArrayRef<int> Mask,
9649                                                 SelectionDAG &DAG) {
9650   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9651                                             "lower single-input shuffles as it "
9652                                             "could then recurse on itself.");
9653   int Size = Mask.size();
9654
9655   // If this can be modeled as a broadcast of two elements followed by a blend,
9656   // prefer that lowering. This is especially important because broadcasts can
9657   // often fold with memory operands.
9658   auto DoBothBroadcast = [&] {
9659     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9660     for (int M : Mask)
9661       if (M >= Size) {
9662         if (V2BroadcastIdx == -1)
9663           V2BroadcastIdx = M - Size;
9664         else if (M - Size != V2BroadcastIdx)
9665           return false;
9666       } else if (M >= 0) {
9667         if (V1BroadcastIdx == -1)
9668           V1BroadcastIdx = M;
9669         else if (M != V1BroadcastIdx)
9670           return false;
9671       }
9672     return true;
9673   };
9674   if (DoBothBroadcast())
9675     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9676                                                       DAG);
9677
9678   // If the inputs all stem from a single 128-bit lane of each input, then we
9679   // split them rather than blending because the split will decompose to
9680   // unusually few instructions.
9681   int LaneCount = VT.getSizeInBits() / 128;
9682   int LaneSize = Size / LaneCount;
9683   SmallBitVector LaneInputs[2];
9684   LaneInputs[0].resize(LaneCount, false);
9685   LaneInputs[1].resize(LaneCount, false);
9686   for (int i = 0; i < Size; ++i)
9687     if (Mask[i] >= 0)
9688       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9689   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9690     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9691
9692   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9693   // that the decomposed single-input shuffles don't end up here.
9694   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9695 }
9696
9697 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9698 /// a permutation and blend of those lanes.
9699 ///
9700 /// This essentially blends the out-of-lane inputs to each lane into the lane
9701 /// from a permuted copy of the vector. This lowering strategy results in four
9702 /// instructions in the worst case for a single-input cross lane shuffle which
9703 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9704 /// of. Special cases for each particular shuffle pattern should be handled
9705 /// prior to trying this lowering.
9706 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9707                                                        SDValue V1, SDValue V2,
9708                                                        ArrayRef<int> Mask,
9709                                                        SelectionDAG &DAG) {
9710   // FIXME: This should probably be generalized for 512-bit vectors as well.
9711   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9712   int LaneSize = Mask.size() / 2;
9713
9714   // If there are only inputs from one 128-bit lane, splitting will in fact be
9715   // less expensive. The flags track whether the given lane contains an element
9716   // that crosses to another lane.
9717   bool LaneCrossing[2] = {false, false};
9718   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9719     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9720       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9721   if (!LaneCrossing[0] || !LaneCrossing[1])
9722     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9723
9724   if (isSingleInputShuffleMask(Mask)) {
9725     SmallVector<int, 32> FlippedBlendMask;
9726     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9727       FlippedBlendMask.push_back(
9728           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9729                                   ? Mask[i]
9730                                   : Mask[i] % LaneSize +
9731                                         (i / LaneSize) * LaneSize + Size));
9732
9733     // Flip the vector, and blend the results which should now be in-lane. The
9734     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9735     // 5 for the high source. The value 3 selects the high half of source 2 and
9736     // the value 2 selects the low half of source 2. We only use source 2 to
9737     // allow folding it into a memory operand.
9738     unsigned PERMMask = 3 | 2 << 4;
9739     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9740                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9741     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9742   }
9743
9744   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9745   // will be handled by the above logic and a blend of the results, much like
9746   // other patterns in AVX.
9747   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9748 }
9749
9750 /// \brief Handle lowering 2-lane 128-bit shuffles.
9751 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9752                                         SDValue V2, ArrayRef<int> Mask,
9753                                         const X86Subtarget *Subtarget,
9754                                         SelectionDAG &DAG) {
9755   // TODO: If minimizing size and one of the inputs is a zero vector and the
9756   // the zero vector has only one use, we could use a VPERM2X128 to save the
9757   // instruction bytes needed to explicitly generate the zero vector.
9758
9759   // Blends are faster and handle all the non-lane-crossing cases.
9760   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9761                                                 Subtarget, DAG))
9762     return Blend;
9763
9764   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9765   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9766
9767   // If either input operand is a zero vector, use VPERM2X128 because its mask
9768   // allows us to replace the zero input with an implicit zero.
9769   if (!IsV1Zero && !IsV2Zero) {
9770     // Check for patterns which can be matched with a single insert of a 128-bit
9771     // subvector.
9772     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9773     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9774       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9775                                    VT.getVectorNumElements() / 2);
9776       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9777                                 DAG.getIntPtrConstant(0, DL));
9778       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9779                                 OnlyUsesV1 ? V1 : V2,
9780                                 DAG.getIntPtrConstant(0, DL));
9781       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9782     }
9783   }
9784
9785   // Otherwise form a 128-bit permutation. After accounting for undefs,
9786   // convert the 64-bit shuffle mask selection values into 128-bit
9787   // selection bits by dividing the indexes by 2 and shifting into positions
9788   // defined by a vperm2*128 instruction's immediate control byte.
9789
9790   // The immediate permute control byte looks like this:
9791   //    [1:0] - select 128 bits from sources for low half of destination
9792   //    [2]   - ignore
9793   //    [3]   - zero low half of destination
9794   //    [5:4] - select 128 bits from sources for high half of destination
9795   //    [6]   - ignore
9796   //    [7]   - zero high half of destination
9797
9798   int MaskLO = Mask[0];
9799   if (MaskLO == SM_SentinelUndef)
9800     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9801
9802   int MaskHI = Mask[2];
9803   if (MaskHI == SM_SentinelUndef)
9804     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9805
9806   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9807
9808   // If either input is a zero vector, replace it with an undef input.
9809   // Shuffle mask values <  4 are selecting elements of V1.
9810   // Shuffle mask values >= 4 are selecting elements of V2.
9811   // Adjust each half of the permute mask by clearing the half that was
9812   // selecting the zero vector and setting the zero mask bit.
9813   if (IsV1Zero) {
9814     V1 = DAG.getUNDEF(VT);
9815     if (MaskLO < 4)
9816       PermMask = (PermMask & 0xf0) | 0x08;
9817     if (MaskHI < 4)
9818       PermMask = (PermMask & 0x0f) | 0x80;
9819   }
9820   if (IsV2Zero) {
9821     V2 = DAG.getUNDEF(VT);
9822     if (MaskLO >= 4)
9823       PermMask = (PermMask & 0xf0) | 0x08;
9824     if (MaskHI >= 4)
9825       PermMask = (PermMask & 0x0f) | 0x80;
9826   }
9827
9828   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9829                      DAG.getConstant(PermMask, DL, MVT::i8));
9830 }
9831
9832 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9833 /// shuffling each lane.
9834 ///
9835 /// This will only succeed when the result of fixing the 128-bit lanes results
9836 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9837 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9838 /// the lane crosses early and then use simpler shuffles within each lane.
9839 ///
9840 /// FIXME: It might be worthwhile at some point to support this without
9841 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9842 /// in x86 only floating point has interesting non-repeating shuffles, and even
9843 /// those are still *marginally* more expensive.
9844 static SDValue lowerVectorShuffleByMerging128BitLanes(
9845     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9846     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9847   assert(!isSingleInputShuffleMask(Mask) &&
9848          "This is only useful with multiple inputs.");
9849
9850   int Size = Mask.size();
9851   int LaneSize = 128 / VT.getScalarSizeInBits();
9852   int NumLanes = Size / LaneSize;
9853   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9854
9855   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9856   // check whether the in-128-bit lane shuffles share a repeating pattern.
9857   SmallVector<int, 4> Lanes;
9858   Lanes.resize(NumLanes, -1);
9859   SmallVector<int, 4> InLaneMask;
9860   InLaneMask.resize(LaneSize, -1);
9861   for (int i = 0; i < Size; ++i) {
9862     if (Mask[i] < 0)
9863       continue;
9864
9865     int j = i / LaneSize;
9866
9867     if (Lanes[j] < 0) {
9868       // First entry we've seen for this lane.
9869       Lanes[j] = Mask[i] / LaneSize;
9870     } else if (Lanes[j] != Mask[i] / LaneSize) {
9871       // This doesn't match the lane selected previously!
9872       return SDValue();
9873     }
9874
9875     // Check that within each lane we have a consistent shuffle mask.
9876     int k = i % LaneSize;
9877     if (InLaneMask[k] < 0) {
9878       InLaneMask[k] = Mask[i] % LaneSize;
9879     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9880       // This doesn't fit a repeating in-lane mask.
9881       return SDValue();
9882     }
9883   }
9884
9885   // First shuffle the lanes into place.
9886   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9887                                 VT.getSizeInBits() / 64);
9888   SmallVector<int, 8> LaneMask;
9889   LaneMask.resize(NumLanes * 2, -1);
9890   for (int i = 0; i < NumLanes; ++i)
9891     if (Lanes[i] >= 0) {
9892       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9893       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9894     }
9895
9896   V1 = DAG.getBitcast(LaneVT, V1);
9897   V2 = DAG.getBitcast(LaneVT, V2);
9898   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9899
9900   // Cast it back to the type we actually want.
9901   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9902
9903   // Now do a simple shuffle that isn't lane crossing.
9904   SmallVector<int, 8> NewMask;
9905   NewMask.resize(Size, -1);
9906   for (int i = 0; i < Size; ++i)
9907     if (Mask[i] >= 0)
9908       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9909   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9910          "Must not introduce lane crosses at this point!");
9911
9912   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9913 }
9914
9915 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9916 /// given mask.
9917 ///
9918 /// This returns true if the elements from a particular input are already in the
9919 /// slot required by the given mask and require no permutation.
9920 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9921   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9922   int Size = Mask.size();
9923   for (int i = 0; i < Size; ++i)
9924     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9925       return false;
9926
9927   return true;
9928 }
9929
9930 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9931                                             ArrayRef<int> Mask, SDValue V1,
9932                                             SDValue V2, SelectionDAG &DAG) {
9933
9934   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9935   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9936   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9937   int NumElts = VT.getVectorNumElements();
9938   bool ShufpdMask = true;
9939   bool CommutableMask = true;
9940   unsigned Immediate = 0;
9941   for (int i = 0; i < NumElts; ++i) {
9942     if (Mask[i] < 0)
9943       continue;
9944     int Val = (i & 6) + NumElts * (i & 1);
9945     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9946     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9947       ShufpdMask = false;
9948     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9949       CommutableMask = false;
9950     Immediate |= (Mask[i] % 2) << i;
9951   }
9952   if (ShufpdMask)
9953     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9954                        DAG.getConstant(Immediate, DL, MVT::i8));
9955   if (CommutableMask)
9956     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9957                        DAG.getConstant(Immediate, DL, MVT::i8));
9958   return SDValue();
9959 }
9960
9961 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9962 ///
9963 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9964 /// isn't available.
9965 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9966                                        const X86Subtarget *Subtarget,
9967                                        SelectionDAG &DAG) {
9968   SDLoc DL(Op);
9969   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9970   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9971   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9972   ArrayRef<int> Mask = SVOp->getMask();
9973   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9974
9975   SmallVector<int, 4> WidenedMask;
9976   if (canWidenShuffleElements(Mask, WidenedMask))
9977     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9978                                     DAG);
9979
9980   if (isSingleInputShuffleMask(Mask)) {
9981     // Check for being able to broadcast a single element.
9982     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9983                                                           Mask, Subtarget, DAG))
9984       return Broadcast;
9985
9986     // Use low duplicate instructions for masks that match their pattern.
9987     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9988       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9989
9990     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9991       // Non-half-crossing single input shuffles can be lowerid with an
9992       // interleaved permutation.
9993       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9994                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9995       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9996                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9997     }
9998
9999     // With AVX2 we have direct support for this permutation.
10000     if (Subtarget->hasAVX2())
10001       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10002                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10003
10004     // Otherwise, fall back.
10005     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10006                                                    DAG);
10007   }
10008
10009   // X86 has dedicated unpack instructions that can handle specific blend
10010   // operations: UNPCKH and UNPCKL.
10011   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10012     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10013   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10014     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10015   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10016     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10017   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10018     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10019
10020   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10021                                                 Subtarget, DAG))
10022     return Blend;
10023
10024   // Check if the blend happens to exactly fit that of SHUFPD.
10025   if (SDValue Op =
10026       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10027     return Op;
10028
10029   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10030   // shuffle. However, if we have AVX2 and either inputs are already in place,
10031   // we will be able to shuffle even across lanes the other input in a single
10032   // instruction so skip this pattern.
10033   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10034                                  isShuffleMaskInputInPlace(1, Mask))))
10035     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10036             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10037       return Result;
10038
10039   // If we have AVX2 then we always want to lower with a blend because an v4 we
10040   // can fully permute the elements.
10041   if (Subtarget->hasAVX2())
10042     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10043                                                       Mask, DAG);
10044
10045   // Otherwise fall back on generic lowering.
10046   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10047 }
10048
10049 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10050 ///
10051 /// This routine is only called when we have AVX2 and thus a reasonable
10052 /// instruction set for v4i64 shuffling..
10053 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10054                                        const X86Subtarget *Subtarget,
10055                                        SelectionDAG &DAG) {
10056   SDLoc DL(Op);
10057   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10058   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10059   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10060   ArrayRef<int> Mask = SVOp->getMask();
10061   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10062   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10063
10064   SmallVector<int, 4> WidenedMask;
10065   if (canWidenShuffleElements(Mask, WidenedMask))
10066     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10067                                     DAG);
10068
10069   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10070                                                 Subtarget, DAG))
10071     return Blend;
10072
10073   // Check for being able to broadcast a single element.
10074   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10075                                                         Mask, Subtarget, DAG))
10076     return Broadcast;
10077
10078   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10079   // use lower latency instructions that will operate on both 128-bit lanes.
10080   SmallVector<int, 2> RepeatedMask;
10081   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10082     if (isSingleInputShuffleMask(Mask)) {
10083       int PSHUFDMask[] = {-1, -1, -1, -1};
10084       for (int i = 0; i < 2; ++i)
10085         if (RepeatedMask[i] >= 0) {
10086           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10087           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10088         }
10089       return DAG.getBitcast(
10090           MVT::v4i64,
10091           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10092                       DAG.getBitcast(MVT::v8i32, V1),
10093                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10094     }
10095   }
10096
10097   // AVX2 provides a direct instruction for permuting a single input across
10098   // lanes.
10099   if (isSingleInputShuffleMask(Mask))
10100     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10101                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10102
10103   // Try to use shift instructions.
10104   if (SDValue Shift =
10105           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10106     return Shift;
10107
10108   // Use dedicated unpack instructions for masks that match their pattern.
10109   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10110     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10111   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10112     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10113   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10114     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10115   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10116     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10117
10118   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10119   // shuffle. However, if we have AVX2 and either inputs are already in place,
10120   // we will be able to shuffle even across lanes the other input in a single
10121   // instruction so skip this pattern.
10122   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10123                                  isShuffleMaskInputInPlace(1, Mask))))
10124     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10125             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10126       return Result;
10127
10128   // Otherwise fall back on generic blend lowering.
10129   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10130                                                     Mask, DAG);
10131 }
10132
10133 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10134 ///
10135 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10136 /// isn't available.
10137 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10138                                        const X86Subtarget *Subtarget,
10139                                        SelectionDAG &DAG) {
10140   SDLoc DL(Op);
10141   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10142   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10143   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10144   ArrayRef<int> Mask = SVOp->getMask();
10145   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10146
10147   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10148                                                 Subtarget, DAG))
10149     return Blend;
10150
10151   // Check for being able to broadcast a single element.
10152   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10153                                                         Mask, Subtarget, DAG))
10154     return Broadcast;
10155
10156   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10157   // options to efficiently lower the shuffle.
10158   SmallVector<int, 4> RepeatedMask;
10159   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10160     assert(RepeatedMask.size() == 4 &&
10161            "Repeated masks must be half the mask width!");
10162
10163     // Use even/odd duplicate instructions for masks that match their pattern.
10164     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10165       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10166     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10167       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10168
10169     if (isSingleInputShuffleMask(Mask))
10170       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10171                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10172
10173     // Use dedicated unpack instructions for masks that match their pattern.
10174     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10175       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10176     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10177       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10178     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10179       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10180     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10181       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10182
10183     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10184     // have already handled any direct blends. We also need to squash the
10185     // repeated mask into a simulated v4f32 mask.
10186     for (int i = 0; i < 4; ++i)
10187       if (RepeatedMask[i] >= 8)
10188         RepeatedMask[i] -= 4;
10189     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10190   }
10191
10192   // If we have a single input shuffle with different shuffle patterns in the
10193   // two 128-bit lanes use the variable mask to VPERMILPS.
10194   if (isSingleInputShuffleMask(Mask)) {
10195     SDValue VPermMask[8];
10196     for (int i = 0; i < 8; ++i)
10197       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10198                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10199     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10200       return DAG.getNode(
10201           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10202           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10203
10204     if (Subtarget->hasAVX2())
10205       return DAG.getNode(
10206           X86ISD::VPERMV, DL, MVT::v8f32,
10207           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10208                                                  MVT::v8i32, VPermMask)),
10209           V1);
10210
10211     // Otherwise, fall back.
10212     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10213                                                    DAG);
10214   }
10215
10216   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10217   // shuffle.
10218   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10219           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10220     return Result;
10221
10222   // If we have AVX2 then we always want to lower with a blend because at v8 we
10223   // can fully permute the elements.
10224   if (Subtarget->hasAVX2())
10225     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10226                                                       Mask, DAG);
10227
10228   // Otherwise fall back on generic lowering.
10229   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10230 }
10231
10232 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10233 ///
10234 /// This routine is only called when we have AVX2 and thus a reasonable
10235 /// instruction set for v8i32 shuffling..
10236 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10237                                        const X86Subtarget *Subtarget,
10238                                        SelectionDAG &DAG) {
10239   SDLoc DL(Op);
10240   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10241   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10242   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10243   ArrayRef<int> Mask = SVOp->getMask();
10244   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10245   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10246
10247   // Whenever we can lower this as a zext, that instruction is strictly faster
10248   // than any alternative. It also allows us to fold memory operands into the
10249   // shuffle in many cases.
10250   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10251                                                          Mask, Subtarget, DAG))
10252     return ZExt;
10253
10254   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10255                                                 Subtarget, DAG))
10256     return Blend;
10257
10258   // Check for being able to broadcast a single element.
10259   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10260                                                         Mask, Subtarget, DAG))
10261     return Broadcast;
10262
10263   // If the shuffle mask is repeated in each 128-bit lane we can use more
10264   // efficient instructions that mirror the shuffles across the two 128-bit
10265   // lanes.
10266   SmallVector<int, 4> RepeatedMask;
10267   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10268     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10269     if (isSingleInputShuffleMask(Mask))
10270       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10271                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10272
10273     // Use dedicated unpack instructions for masks that match their pattern.
10274     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10275       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10276     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10277       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10278     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10279       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10280     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10281       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10282   }
10283
10284   // Try to use shift instructions.
10285   if (SDValue Shift =
10286           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10287     return Shift;
10288
10289   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10290           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10291     return Rotate;
10292
10293   // If the shuffle patterns aren't repeated but it is a single input, directly
10294   // generate a cross-lane VPERMD instruction.
10295   if (isSingleInputShuffleMask(Mask)) {
10296     SDValue VPermMask[8];
10297     for (int i = 0; i < 8; ++i)
10298       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10299                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10300     return DAG.getNode(
10301         X86ISD::VPERMV, DL, MVT::v8i32,
10302         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10303   }
10304
10305   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10306   // shuffle.
10307   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10308           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10309     return Result;
10310
10311   // Otherwise fall back on generic blend lowering.
10312   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10313                                                     Mask, DAG);
10314 }
10315
10316 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10317 ///
10318 /// This routine is only called when we have AVX2 and thus a reasonable
10319 /// instruction set for v16i16 shuffling..
10320 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10321                                         const X86Subtarget *Subtarget,
10322                                         SelectionDAG &DAG) {
10323   SDLoc DL(Op);
10324   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10325   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10326   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10327   ArrayRef<int> Mask = SVOp->getMask();
10328   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10329   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10330
10331   // Whenever we can lower this as a zext, that instruction is strictly faster
10332   // than any alternative. It also allows us to fold memory operands into the
10333   // shuffle in many cases.
10334   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10335                                                          Mask, Subtarget, DAG))
10336     return ZExt;
10337
10338   // Check for being able to broadcast a single element.
10339   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10340                                                         Mask, Subtarget, DAG))
10341     return Broadcast;
10342
10343   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10344                                                 Subtarget, DAG))
10345     return Blend;
10346
10347   // Use dedicated unpack instructions for masks that match their pattern.
10348   if (isShuffleEquivalent(V1, V2, Mask,
10349                           {// First 128-bit lane:
10350                            0, 16, 1, 17, 2, 18, 3, 19,
10351                            // Second 128-bit lane:
10352                            8, 24, 9, 25, 10, 26, 11, 27}))
10353     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10354   if (isShuffleEquivalent(V1, V2, Mask,
10355                           {// First 128-bit lane:
10356                            4, 20, 5, 21, 6, 22, 7, 23,
10357                            // Second 128-bit lane:
10358                            12, 28, 13, 29, 14, 30, 15, 31}))
10359     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10360
10361   // Try to use shift instructions.
10362   if (SDValue Shift =
10363           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10364     return Shift;
10365
10366   // Try to use byte rotation instructions.
10367   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10368           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10369     return Rotate;
10370
10371   if (isSingleInputShuffleMask(Mask)) {
10372     // There are no generalized cross-lane shuffle operations available on i16
10373     // element types.
10374     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10375       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10376                                                      Mask, DAG);
10377
10378     SmallVector<int, 8> RepeatedMask;
10379     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10380       // As this is a single-input shuffle, the repeated mask should be
10381       // a strictly valid v8i16 mask that we can pass through to the v8i16
10382       // lowering to handle even the v16 case.
10383       return lowerV8I16GeneralSingleInputVectorShuffle(
10384           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10385     }
10386
10387     SDValue PSHUFBMask[32];
10388     for (int i = 0; i < 16; ++i) {
10389       if (Mask[i] == -1) {
10390         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10391         continue;
10392       }
10393
10394       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10395       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10396       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10397       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10398     }
10399     return DAG.getBitcast(MVT::v16i16,
10400                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10401                                       DAG.getBitcast(MVT::v32i8, V1),
10402                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10403                                                   MVT::v32i8, PSHUFBMask)));
10404   }
10405
10406   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10407   // shuffle.
10408   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10409           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10410     return Result;
10411
10412   // Otherwise fall back on generic lowering.
10413   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10414 }
10415
10416 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10417 ///
10418 /// This routine is only called when we have AVX2 and thus a reasonable
10419 /// instruction set for v32i8 shuffling..
10420 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10421                                        const X86Subtarget *Subtarget,
10422                                        SelectionDAG &DAG) {
10423   SDLoc DL(Op);
10424   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10425   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10426   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10427   ArrayRef<int> Mask = SVOp->getMask();
10428   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10429   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10430
10431   // Whenever we can lower this as a zext, that instruction is strictly faster
10432   // than any alternative. It also allows us to fold memory operands into the
10433   // shuffle in many cases.
10434   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10435                                                          Mask, Subtarget, DAG))
10436     return ZExt;
10437
10438   // Check for being able to broadcast a single element.
10439   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10440                                                         Mask, Subtarget, DAG))
10441     return Broadcast;
10442
10443   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10444                                                 Subtarget, DAG))
10445     return Blend;
10446
10447   // Use dedicated unpack instructions for masks that match their pattern.
10448   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10449   // 256-bit lanes.
10450   if (isShuffleEquivalent(
10451           V1, V2, Mask,
10452           {// First 128-bit lane:
10453            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10454            // Second 128-bit lane:
10455            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10456     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10457   if (isShuffleEquivalent(
10458           V1, V2, Mask,
10459           {// First 128-bit lane:
10460            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10461            // Second 128-bit lane:
10462            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10463     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10464
10465   // Try to use shift instructions.
10466   if (SDValue Shift =
10467           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10468     return Shift;
10469
10470   // Try to use byte rotation instructions.
10471   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10472           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10473     return Rotate;
10474
10475   if (isSingleInputShuffleMask(Mask)) {
10476     // There are no generalized cross-lane shuffle operations available on i8
10477     // element types.
10478     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10479       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10480                                                      Mask, DAG);
10481
10482     SDValue PSHUFBMask[32];
10483     for (int i = 0; i < 32; ++i)
10484       PSHUFBMask[i] =
10485           Mask[i] < 0
10486               ? DAG.getUNDEF(MVT::i8)
10487               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10488                                 MVT::i8);
10489
10490     return DAG.getNode(
10491         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10492         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10493   }
10494
10495   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10496   // shuffle.
10497   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10498           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10499     return Result;
10500
10501   // Otherwise fall back on generic lowering.
10502   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10503 }
10504
10505 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10506 ///
10507 /// This routine either breaks down the specific type of a 256-bit x86 vector
10508 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10509 /// together based on the available instructions.
10510 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10511                                         MVT VT, const X86Subtarget *Subtarget,
10512                                         SelectionDAG &DAG) {
10513   SDLoc DL(Op);
10514   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10515   ArrayRef<int> Mask = SVOp->getMask();
10516
10517   // If we have a single input to the zero element, insert that into V1 if we
10518   // can do so cheaply.
10519   int NumElts = VT.getVectorNumElements();
10520   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10521     return M >= NumElts;
10522   });
10523
10524   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10525     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10526                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10527       return Insertion;
10528
10529   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10530   // check for those subtargets here and avoid much of the subtarget querying in
10531   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10532   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10533   // floating point types there eventually, just immediately cast everything to
10534   // a float and operate entirely in that domain.
10535   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10536     int ElementBits = VT.getScalarSizeInBits();
10537     if (ElementBits < 32)
10538       // No floating point type available, decompose into 128-bit vectors.
10539       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10540
10541     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10542                                 VT.getVectorNumElements());
10543     V1 = DAG.getBitcast(FpVT, V1);
10544     V2 = DAG.getBitcast(FpVT, V2);
10545     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10546   }
10547
10548   switch (VT.SimpleTy) {
10549   case MVT::v4f64:
10550     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10551   case MVT::v4i64:
10552     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10553   case MVT::v8f32:
10554     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10555   case MVT::v8i32:
10556     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10557   case MVT::v16i16:
10558     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10559   case MVT::v32i8:
10560     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10561
10562   default:
10563     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10564   }
10565 }
10566
10567 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10568                                            ArrayRef<int> Mask, SDValue V1,
10569                                            SDValue V2, SelectionDAG &DAG) {
10570
10571   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10572
10573   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10574   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10575
10576   SmallVector<SDValue, 32>  VPermMask;
10577   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10578     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10579                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10580   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10581                                  VPermMask);
10582   if (isSingleInputShuffleMask(Mask))
10583     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10584
10585   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10586 }
10587
10588 // X86 has dedicated unpack instructions that can handle specific blend
10589 // operations: UNPCKH and UNPCKL.
10590 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT,
10591                                            ArrayRef<int> Mask, SDValue V1,
10592                                            SDValue V2, SelectionDAG &DAG) {
10593   int NumElts = VT.getVectorNumElements();
10594   bool Unpckl = true;
10595   bool Unpckh = true;
10596   bool UnpcklSwapped = true;
10597   bool UnpckhSwapped = true;
10598   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
10599
10600   for (int i = 0; i < NumElts ; ++i) {
10601     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
10602
10603     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
10604     int HiPos = LoPos + NumEltsInLane / 2;
10605     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
10606     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
10607
10608     if (Mask[i] == -1)
10609       continue;
10610     if (Mask[i] != LoPos)
10611       Unpckl = false;
10612     if (Mask[i] != HiPos)
10613       Unpckh = false;
10614     if (Mask[i] != LoPosSwapped)
10615       UnpcklSwapped = false;
10616     if (Mask[i] != HiPosSwapped)
10617       UnpckhSwapped = false;
10618     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
10619       return SDValue();
10620   }
10621   if (Unpckl)
10622     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10623   if (Unpckh)
10624     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10625   if (UnpcklSwapped)
10626     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10627   if (UnpckhSwapped)
10628     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10629
10630   llvm_unreachable("Unexpected result of UNPCK mask analysis");
10631   return SDValue();
10632 }
10633
10634 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10635 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10636                                        const X86Subtarget *Subtarget,
10637                                        SelectionDAG &DAG) {
10638   SDLoc DL(Op);
10639   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10640   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10641   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10642   ArrayRef<int> Mask = SVOp->getMask();
10643   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10644
10645   SDValue UnpckNode =
10646        lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG);
10647   if (UnpckNode)
10648     return UnpckNode;
10649
10650   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10651 }
10652
10653 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10654 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10655                                        const X86Subtarget *Subtarget,
10656                                        SelectionDAG &DAG) {
10657   SDLoc DL(Op);
10658   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10659   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10660   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10661   ArrayRef<int> Mask = SVOp->getMask();
10662   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10663
10664   SDValue UnpckNode =
10665        lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG);
10666   if (UnpckNode)
10667     return UnpckNode;
10668
10669   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10670 }
10671
10672 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10673 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10674                                        const X86Subtarget *Subtarget,
10675                                        SelectionDAG &DAG) {
10676   SDLoc DL(Op);
10677   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10678   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10679   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10680   ArrayRef<int> Mask = SVOp->getMask();
10681   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10682
10683   SDValue UnpckNode =
10684        lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG);
10685   if (UnpckNode)
10686     return UnpckNode;
10687
10688   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10689 }
10690
10691 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10692 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10693                                        const X86Subtarget *Subtarget,
10694                                        SelectionDAG &DAG) {
10695   SDLoc DL(Op);
10696   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10697   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10698   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10699   ArrayRef<int> Mask = SVOp->getMask();
10700   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10701
10702   SDValue UnpckNode =
10703        lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG);
10704   if (UnpckNode)
10705     return UnpckNode;
10706
10707   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10708 }
10709
10710 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10711 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10712                                         const X86Subtarget *Subtarget,
10713                                         SelectionDAG &DAG) {
10714   SDLoc DL(Op);
10715   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10716   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10718   ArrayRef<int> Mask = SVOp->getMask();
10719   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10720   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10721
10722   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10723 }
10724
10725 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10726 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10727                                        const X86Subtarget *Subtarget,
10728                                        SelectionDAG &DAG) {
10729   SDLoc DL(Op);
10730   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10731   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10732   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10733   ArrayRef<int> Mask = SVOp->getMask();
10734   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10735   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10736
10737   // FIXME: Implement direct support for this type!
10738   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10739 }
10740
10741 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10742 ///
10743 /// This routine either breaks down the specific type of a 512-bit x86 vector
10744 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10745 /// together based on the available instructions.
10746 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10747                                         MVT VT, const X86Subtarget *Subtarget,
10748                                         SelectionDAG &DAG) {
10749   SDLoc DL(Op);
10750   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10751   ArrayRef<int> Mask = SVOp->getMask();
10752   assert(Subtarget->hasAVX512() &&
10753          "Cannot lower 512-bit vectors w/ basic ISA!");
10754
10755   // Check for being able to broadcast a single element.
10756   if (SDValue Broadcast =
10757           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10758     return Broadcast;
10759
10760   // Dispatch to each element type for lowering. If we don't have supprot for
10761   // specific element type shuffles at 512 bits, immediately split them and
10762   // lower them. Each lowering routine of a given type is allowed to assume that
10763   // the requisite ISA extensions for that element type are available.
10764   switch (VT.SimpleTy) {
10765   case MVT::v8f64:
10766     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10767   case MVT::v16f32:
10768     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10769   case MVT::v8i64:
10770     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10771   case MVT::v16i32:
10772     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10773   case MVT::v32i16:
10774     if (Subtarget->hasBWI())
10775       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10776     break;
10777   case MVT::v64i8:
10778     if (Subtarget->hasBWI())
10779       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10780     break;
10781
10782   default:
10783     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10784   }
10785
10786   // Otherwise fall back on splitting.
10787   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10788 }
10789
10790 /// \brief Top-level lowering for x86 vector shuffles.
10791 ///
10792 /// This handles decomposition, canonicalization, and lowering of all x86
10793 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10794 /// above in helper routines. The canonicalization attempts to widen shuffles
10795 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10796 /// s.t. only one of the two inputs needs to be tested, etc.
10797 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10798                                   SelectionDAG &DAG) {
10799   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10800   ArrayRef<int> Mask = SVOp->getMask();
10801   SDValue V1 = Op.getOperand(0);
10802   SDValue V2 = Op.getOperand(1);
10803   MVT VT = Op.getSimpleValueType();
10804   int NumElements = VT.getVectorNumElements();
10805   SDLoc dl(Op);
10806
10807   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10808
10809   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10810   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10811   if (V1IsUndef && V2IsUndef)
10812     return DAG.getUNDEF(VT);
10813
10814   // When we create a shuffle node we put the UNDEF node to second operand,
10815   // but in some cases the first operand may be transformed to UNDEF.
10816   // In this case we should just commute the node.
10817   if (V1IsUndef)
10818     return DAG.getCommutedVectorShuffle(*SVOp);
10819
10820   // Check for non-undef masks pointing at an undef vector and make the masks
10821   // undef as well. This makes it easier to match the shuffle based solely on
10822   // the mask.
10823   if (V2IsUndef)
10824     for (int M : Mask)
10825       if (M >= NumElements) {
10826         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10827         for (int &M : NewMask)
10828           if (M >= NumElements)
10829             M = -1;
10830         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10831       }
10832
10833   // We actually see shuffles that are entirely re-arrangements of a set of
10834   // zero inputs. This mostly happens while decomposing complex shuffles into
10835   // simple ones. Directly lower these as a buildvector of zeros.
10836   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10837   if (Zeroable.all())
10838     return getZeroVector(VT, Subtarget, DAG, dl);
10839
10840   // Try to collapse shuffles into using a vector type with fewer elements but
10841   // wider element types. We cap this to not form integers or floating point
10842   // elements wider than 64 bits, but it might be interesting to form i128
10843   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10844   SmallVector<int, 16> WidenedMask;
10845   if (VT.getScalarSizeInBits() < 64 &&
10846       canWidenShuffleElements(Mask, WidenedMask)) {
10847     MVT NewEltVT = VT.isFloatingPoint()
10848                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10849                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10850     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10851     // Make sure that the new vector type is legal. For example, v2f64 isn't
10852     // legal on SSE1.
10853     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10854       V1 = DAG.getBitcast(NewVT, V1);
10855       V2 = DAG.getBitcast(NewVT, V2);
10856       return DAG.getBitcast(
10857           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10858     }
10859   }
10860
10861   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10862   for (int M : SVOp->getMask())
10863     if (M < 0)
10864       ++NumUndefElements;
10865     else if (M < NumElements)
10866       ++NumV1Elements;
10867     else
10868       ++NumV2Elements;
10869
10870   // Commute the shuffle as needed such that more elements come from V1 than
10871   // V2. This allows us to match the shuffle pattern strictly on how many
10872   // elements come from V1 without handling the symmetric cases.
10873   if (NumV2Elements > NumV1Elements)
10874     return DAG.getCommutedVectorShuffle(*SVOp);
10875
10876   // When the number of V1 and V2 elements are the same, try to minimize the
10877   // number of uses of V2 in the low half of the vector. When that is tied,
10878   // ensure that the sum of indices for V1 is equal to or lower than the sum
10879   // indices for V2. When those are equal, try to ensure that the number of odd
10880   // indices for V1 is lower than the number of odd indices for V2.
10881   if (NumV1Elements == NumV2Elements) {
10882     int LowV1Elements = 0, LowV2Elements = 0;
10883     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10884       if (M >= NumElements)
10885         ++LowV2Elements;
10886       else if (M >= 0)
10887         ++LowV1Elements;
10888     if (LowV2Elements > LowV1Elements) {
10889       return DAG.getCommutedVectorShuffle(*SVOp);
10890     } else if (LowV2Elements == LowV1Elements) {
10891       int SumV1Indices = 0, SumV2Indices = 0;
10892       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10893         if (SVOp->getMask()[i] >= NumElements)
10894           SumV2Indices += i;
10895         else if (SVOp->getMask()[i] >= 0)
10896           SumV1Indices += i;
10897       if (SumV2Indices < SumV1Indices) {
10898         return DAG.getCommutedVectorShuffle(*SVOp);
10899       } else if (SumV2Indices == SumV1Indices) {
10900         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10901         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10902           if (SVOp->getMask()[i] >= NumElements)
10903             NumV2OddIndices += i % 2;
10904           else if (SVOp->getMask()[i] >= 0)
10905             NumV1OddIndices += i % 2;
10906         if (NumV2OddIndices < NumV1OddIndices)
10907           return DAG.getCommutedVectorShuffle(*SVOp);
10908       }
10909     }
10910   }
10911
10912   // For each vector width, delegate to a specialized lowering routine.
10913   if (VT.getSizeInBits() == 128)
10914     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10915
10916   if (VT.getSizeInBits() == 256)
10917     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10918
10919   if (VT.getSizeInBits() == 512)
10920     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10921
10922   llvm_unreachable("Unimplemented!");
10923 }
10924
10925 // This function assumes its argument is a BUILD_VECTOR of constants or
10926 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10927 // true.
10928 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10929                                     unsigned &MaskValue) {
10930   MaskValue = 0;
10931   unsigned NumElems = BuildVector->getNumOperands();
10932   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10933   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10934   unsigned NumElemsInLane = NumElems / NumLanes;
10935
10936   // Blend for v16i16 should be symmetric for the both lanes.
10937   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10938     SDValue EltCond = BuildVector->getOperand(i);
10939     SDValue SndLaneEltCond =
10940         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10941
10942     int Lane1Cond = -1, Lane2Cond = -1;
10943     if (isa<ConstantSDNode>(EltCond))
10944       Lane1Cond = !isZero(EltCond);
10945     if (isa<ConstantSDNode>(SndLaneEltCond))
10946       Lane2Cond = !isZero(SndLaneEltCond);
10947
10948     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10949       // Lane1Cond != 0, means we want the first argument.
10950       // Lane1Cond == 0, means we want the second argument.
10951       // The encoding of this argument is 0 for the first argument, 1
10952       // for the second. Therefore, invert the condition.
10953       MaskValue |= !Lane1Cond << i;
10954     else if (Lane1Cond < 0)
10955       MaskValue |= !Lane2Cond << i;
10956     else
10957       return false;
10958   }
10959   return true;
10960 }
10961
10962 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10963 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10964                                            const X86Subtarget *Subtarget,
10965                                            SelectionDAG &DAG) {
10966   SDValue Cond = Op.getOperand(0);
10967   SDValue LHS = Op.getOperand(1);
10968   SDValue RHS = Op.getOperand(2);
10969   SDLoc dl(Op);
10970   MVT VT = Op.getSimpleValueType();
10971
10972   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10973     return SDValue();
10974   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10975
10976   // Only non-legal VSELECTs reach this lowering, convert those into generic
10977   // shuffles and re-use the shuffle lowering path for blends.
10978   SmallVector<int, 32> Mask;
10979   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10980     SDValue CondElt = CondBV->getOperand(i);
10981     Mask.push_back(
10982         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10983   }
10984   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10985 }
10986
10987 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10988   // A vselect where all conditions and data are constants can be optimized into
10989   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10990   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10991       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10992       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10993     return SDValue();
10994
10995   // Try to lower this to a blend-style vector shuffle. This can handle all
10996   // constant condition cases.
10997   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10998     return BlendOp;
10999
11000   // Variable blends are only legal from SSE4.1 onward.
11001   if (!Subtarget->hasSSE41())
11002     return SDValue();
11003
11004   // Only some types will be legal on some subtargets. If we can emit a legal
11005   // VSELECT-matching blend, return Op, and but if we need to expand, return
11006   // a null value.
11007   switch (Op.getSimpleValueType().SimpleTy) {
11008   default:
11009     // Most of the vector types have blends past SSE4.1.
11010     return Op;
11011
11012   case MVT::v32i8:
11013     // The byte blends for AVX vectors were introduced only in AVX2.
11014     if (Subtarget->hasAVX2())
11015       return Op;
11016
11017     return SDValue();
11018
11019   case MVT::v8i16:
11020   case MVT::v16i16:
11021     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11022     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11023       return Op;
11024
11025     // FIXME: We should custom lower this by fixing the condition and using i8
11026     // blends.
11027     return SDValue();
11028   }
11029 }
11030
11031 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11032   MVT VT = Op.getSimpleValueType();
11033   SDLoc dl(Op);
11034
11035   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11036     return SDValue();
11037
11038   if (VT.getSizeInBits() == 8) {
11039     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11040                                   Op.getOperand(0), Op.getOperand(1));
11041     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11042                                   DAG.getValueType(VT));
11043     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11044   }
11045
11046   if (VT.getSizeInBits() == 16) {
11047     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11048     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11049     if (Idx == 0)
11050       return DAG.getNode(
11051           ISD::TRUNCATE, dl, MVT::i16,
11052           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11053                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11054                       Op.getOperand(1)));
11055     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11056                                   Op.getOperand(0), Op.getOperand(1));
11057     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11058                                   DAG.getValueType(VT));
11059     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11060   }
11061
11062   if (VT == MVT::f32) {
11063     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11064     // the result back to FR32 register. It's only worth matching if the
11065     // result has a single use which is a store or a bitcast to i32.  And in
11066     // the case of a store, it's not worth it if the index is a constant 0,
11067     // because a MOVSSmr can be used instead, which is smaller and faster.
11068     if (!Op.hasOneUse())
11069       return SDValue();
11070     SDNode *User = *Op.getNode()->use_begin();
11071     if ((User->getOpcode() != ISD::STORE ||
11072          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11073           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11074         (User->getOpcode() != ISD::BITCAST ||
11075          User->getValueType(0) != MVT::i32))
11076       return SDValue();
11077     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11078                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11079                                   Op.getOperand(1));
11080     return DAG.getBitcast(MVT::f32, Extract);
11081   }
11082
11083   if (VT == MVT::i32 || VT == MVT::i64) {
11084     // ExtractPS/pextrq works with constant index.
11085     if (isa<ConstantSDNode>(Op.getOperand(1)))
11086       return Op;
11087   }
11088   return SDValue();
11089 }
11090
11091 /// Extract one bit from mask vector, like v16i1 or v8i1.
11092 /// AVX-512 feature.
11093 SDValue
11094 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11095   SDValue Vec = Op.getOperand(0);
11096   SDLoc dl(Vec);
11097   MVT VecVT = Vec.getSimpleValueType();
11098   SDValue Idx = Op.getOperand(1);
11099   MVT EltVT = Op.getSimpleValueType();
11100
11101   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11102   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11103          "Unexpected vector type in ExtractBitFromMaskVector");
11104
11105   // variable index can't be handled in mask registers,
11106   // extend vector to VR512
11107   if (!isa<ConstantSDNode>(Idx)) {
11108     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11109     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11110     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11111                               ExtVT.getVectorElementType(), Ext, Idx);
11112     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11113   }
11114
11115   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11116   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11117   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11118     rc = getRegClassFor(MVT::v16i1);
11119   unsigned MaxSift = rc->getSize()*8 - 1;
11120   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11121                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11122   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11123                     DAG.getConstant(MaxSift, dl, MVT::i8));
11124   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11125                        DAG.getIntPtrConstant(0, dl));
11126 }
11127
11128 SDValue
11129 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11130                                            SelectionDAG &DAG) const {
11131   SDLoc dl(Op);
11132   SDValue Vec = Op.getOperand(0);
11133   MVT VecVT = Vec.getSimpleValueType();
11134   SDValue Idx = Op.getOperand(1);
11135
11136   if (Op.getSimpleValueType() == MVT::i1)
11137     return ExtractBitFromMaskVector(Op, DAG);
11138
11139   if (!isa<ConstantSDNode>(Idx)) {
11140     if (VecVT.is512BitVector() ||
11141         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11142          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11143
11144       MVT MaskEltVT =
11145         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11146       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11147                                     MaskEltVT.getSizeInBits());
11148
11149       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11150       auto PtrVT = getPointerTy(DAG.getDataLayout());
11151       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11152                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11153                                  DAG.getConstant(0, dl, PtrVT));
11154       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11155       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11156                          DAG.getConstant(0, dl, PtrVT));
11157     }
11158     return SDValue();
11159   }
11160
11161   // If this is a 256-bit vector result, first extract the 128-bit vector and
11162   // then extract the element from the 128-bit vector.
11163   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11164
11165     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11166     // Get the 128-bit vector.
11167     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11168     MVT EltVT = VecVT.getVectorElementType();
11169
11170     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11171
11172     //if (IdxVal >= NumElems/2)
11173     //  IdxVal -= NumElems/2;
11174     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11175     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11176                        DAG.getConstant(IdxVal, dl, MVT::i32));
11177   }
11178
11179   assert(VecVT.is128BitVector() && "Unexpected vector length");
11180
11181   if (Subtarget->hasSSE41())
11182     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11183       return Res;
11184
11185   MVT VT = Op.getSimpleValueType();
11186   // TODO: handle v16i8.
11187   if (VT.getSizeInBits() == 16) {
11188     SDValue Vec = Op.getOperand(0);
11189     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11190     if (Idx == 0)
11191       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11192                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11193                                      DAG.getBitcast(MVT::v4i32, Vec),
11194                                      Op.getOperand(1)));
11195     // Transform it so it match pextrw which produces a 32-bit result.
11196     MVT EltVT = MVT::i32;
11197     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11198                                   Op.getOperand(0), Op.getOperand(1));
11199     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11200                                   DAG.getValueType(VT));
11201     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11202   }
11203
11204   if (VT.getSizeInBits() == 32) {
11205     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11206     if (Idx == 0)
11207       return Op;
11208
11209     // SHUFPS the element to the lowest double word, then movss.
11210     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11211     MVT VVT = Op.getOperand(0).getSimpleValueType();
11212     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11213                                        DAG.getUNDEF(VVT), Mask);
11214     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11215                        DAG.getIntPtrConstant(0, dl));
11216   }
11217
11218   if (VT.getSizeInBits() == 64) {
11219     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11220     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11221     //        to match extract_elt for f64.
11222     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11223     if (Idx == 0)
11224       return Op;
11225
11226     // UNPCKHPD the element to the lowest double word, then movsd.
11227     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11228     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11229     int Mask[2] = { 1, -1 };
11230     MVT VVT = Op.getOperand(0).getSimpleValueType();
11231     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11232                                        DAG.getUNDEF(VVT), Mask);
11233     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11234                        DAG.getIntPtrConstant(0, dl));
11235   }
11236
11237   return SDValue();
11238 }
11239
11240 /// Insert one bit to mask vector, like v16i1 or v8i1.
11241 /// AVX-512 feature.
11242 SDValue
11243 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11244   SDLoc dl(Op);
11245   SDValue Vec = Op.getOperand(0);
11246   SDValue Elt = Op.getOperand(1);
11247   SDValue Idx = Op.getOperand(2);
11248   MVT VecVT = Vec.getSimpleValueType();
11249
11250   if (!isa<ConstantSDNode>(Idx)) {
11251     // Non constant index. Extend source and destination,
11252     // insert element and then truncate the result.
11253     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11254     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11255     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11256       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11257       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11258     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11259   }
11260
11261   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11262   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11263   if (IdxVal)
11264     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11265                            DAG.getConstant(IdxVal, dl, MVT::i8));
11266   if (Vec.getOpcode() == ISD::UNDEF)
11267     return EltInVec;
11268   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11269 }
11270
11271 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11272                                                   SelectionDAG &DAG) const {
11273   MVT VT = Op.getSimpleValueType();
11274   MVT EltVT = VT.getVectorElementType();
11275
11276   if (EltVT == MVT::i1)
11277     return InsertBitToMaskVector(Op, DAG);
11278
11279   SDLoc dl(Op);
11280   SDValue N0 = Op.getOperand(0);
11281   SDValue N1 = Op.getOperand(1);
11282   SDValue N2 = Op.getOperand(2);
11283   if (!isa<ConstantSDNode>(N2))
11284     return SDValue();
11285   auto *N2C = cast<ConstantSDNode>(N2);
11286   unsigned IdxVal = N2C->getZExtValue();
11287
11288   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11289   // into that, and then insert the subvector back into the result.
11290   if (VT.is256BitVector() || VT.is512BitVector()) {
11291     // With a 256-bit vector, we can insert into the zero element efficiently
11292     // using a blend if we have AVX or AVX2 and the right data type.
11293     if (VT.is256BitVector() && IdxVal == 0) {
11294       // TODO: It is worthwhile to cast integer to floating point and back
11295       // and incur a domain crossing penalty if that's what we'll end up
11296       // doing anyway after extracting to a 128-bit vector.
11297       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11298           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11299         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11300         N2 = DAG.getIntPtrConstant(1, dl);
11301         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11302       }
11303     }
11304
11305     // Get the desired 128-bit vector chunk.
11306     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11307
11308     // Insert the element into the desired chunk.
11309     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11310     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11311
11312     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11313                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11314
11315     // Insert the changed part back into the bigger vector
11316     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11317   }
11318   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11319
11320   if (Subtarget->hasSSE41()) {
11321     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11322       unsigned Opc;
11323       if (VT == MVT::v8i16) {
11324         Opc = X86ISD::PINSRW;
11325       } else {
11326         assert(VT == MVT::v16i8);
11327         Opc = X86ISD::PINSRB;
11328       }
11329
11330       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11331       // argument.
11332       if (N1.getValueType() != MVT::i32)
11333         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11334       if (N2.getValueType() != MVT::i32)
11335         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11336       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11337     }
11338
11339     if (EltVT == MVT::f32) {
11340       // Bits [7:6] of the constant are the source select. This will always be
11341       //   zero here. The DAG Combiner may combine an extract_elt index into
11342       //   these bits. For example (insert (extract, 3), 2) could be matched by
11343       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11344       // Bits [5:4] of the constant are the destination select. This is the
11345       //   value of the incoming immediate.
11346       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11347       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11348
11349       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11350       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11351         // If this is an insertion of 32-bits into the low 32-bits of
11352         // a vector, we prefer to generate a blend with immediate rather
11353         // than an insertps. Blends are simpler operations in hardware and so
11354         // will always have equal or better performance than insertps.
11355         // But if optimizing for size and there's a load folding opportunity,
11356         // generate insertps because blendps does not have a 32-bit memory
11357         // operand form.
11358         N2 = DAG.getIntPtrConstant(1, dl);
11359         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11360         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11361       }
11362       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11363       // Create this as a scalar to vector..
11364       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11365       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11366     }
11367
11368     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11369       // PINSR* works with constant index.
11370       return Op;
11371     }
11372   }
11373
11374   if (EltVT == MVT::i8)
11375     return SDValue();
11376
11377   if (EltVT.getSizeInBits() == 16) {
11378     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11379     // as its second argument.
11380     if (N1.getValueType() != MVT::i32)
11381       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11382     if (N2.getValueType() != MVT::i32)
11383       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11384     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11385   }
11386   return SDValue();
11387 }
11388
11389 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11390   SDLoc dl(Op);
11391   MVT OpVT = Op.getSimpleValueType();
11392
11393   // If this is a 256-bit vector result, first insert into a 128-bit
11394   // vector and then insert into the 256-bit vector.
11395   if (!OpVT.is128BitVector()) {
11396     // Insert into a 128-bit vector.
11397     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11398     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11399                                  OpVT.getVectorNumElements() / SizeFactor);
11400
11401     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11402
11403     // Insert the 128-bit vector.
11404     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11405   }
11406
11407   if (OpVT == MVT::v1i64 &&
11408       Op.getOperand(0).getValueType() == MVT::i64)
11409     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11410
11411   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11412   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11413   return DAG.getBitcast(
11414       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11415 }
11416
11417 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11418 // a simple subregister reference or explicit instructions to grab
11419 // upper bits of a vector.
11420 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11421                                       SelectionDAG &DAG) {
11422   SDLoc dl(Op);
11423   SDValue In =  Op.getOperand(0);
11424   SDValue Idx = Op.getOperand(1);
11425   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11426   MVT ResVT   = Op.getSimpleValueType();
11427   MVT InVT    = In.getSimpleValueType();
11428
11429   if (Subtarget->hasFp256()) {
11430     if (ResVT.is128BitVector() &&
11431         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11432         isa<ConstantSDNode>(Idx)) {
11433       return Extract128BitVector(In, IdxVal, DAG, dl);
11434     }
11435     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11436         isa<ConstantSDNode>(Idx)) {
11437       return Extract256BitVector(In, IdxVal, DAG, dl);
11438     }
11439   }
11440   return SDValue();
11441 }
11442
11443 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11444 // simple superregister reference or explicit instructions to insert
11445 // the upper bits of a vector.
11446 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11447                                      SelectionDAG &DAG) {
11448   if (!Subtarget->hasAVX())
11449     return SDValue();
11450
11451   SDLoc dl(Op);
11452   SDValue Vec = Op.getOperand(0);
11453   SDValue SubVec = Op.getOperand(1);
11454   SDValue Idx = Op.getOperand(2);
11455
11456   if (!isa<ConstantSDNode>(Idx))
11457     return SDValue();
11458
11459   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11460   MVT OpVT = Op.getSimpleValueType();
11461   MVT SubVecVT = SubVec.getSimpleValueType();
11462
11463   // Fold two 16-byte subvector loads into one 32-byte load:
11464   // (insert_subvector (insert_subvector undef, (load addr), 0),
11465   //                   (load addr + 16), Elts/2)
11466   // --> load32 addr
11467   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11468       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11469       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11470     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11471     if (Idx2 && Idx2->getZExtValue() == 0) {
11472       SDValue SubVec2 = Vec.getOperand(1);
11473       // If needed, look through a bitcast to get to the load.
11474       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11475         SubVec2 = SubVec2.getOperand(0);
11476       
11477       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11478         bool Fast;
11479         unsigned Alignment = FirstLd->getAlignment();
11480         unsigned AS = FirstLd->getAddressSpace();
11481         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11482         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11483                                     OpVT, AS, Alignment, &Fast) && Fast) {
11484           SDValue Ops[] = { SubVec2, SubVec };
11485           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11486             return Ld;
11487         }
11488       }
11489     }
11490   }
11491
11492   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11493       SubVecVT.is128BitVector())
11494     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11495
11496   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11497     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11498
11499   if (OpVT.getVectorElementType() == MVT::i1) {
11500     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11501       return Op;
11502     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11503     SDValue Undef = DAG.getUNDEF(OpVT);
11504     unsigned NumElems = OpVT.getVectorNumElements();
11505     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11506
11507     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11508       // Zero upper bits of the Vec
11509       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11510       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11511
11512       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11513                                  SubVec, ZeroIdx);
11514       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11515       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11516     }
11517     if (IdxVal == 0) {
11518       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11519                                  SubVec, ZeroIdx);
11520       // Zero upper bits of the Vec2
11521       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11522       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11523       // Zero lower bits of the Vec
11524       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11525       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11526       // Merge them together
11527       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11528     }
11529   }
11530   return SDValue();
11531 }
11532
11533 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11534 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11535 // one of the above mentioned nodes. It has to be wrapped because otherwise
11536 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11537 // be used to form addressing mode. These wrapped nodes will be selected
11538 // into MOV32ri.
11539 SDValue
11540 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11541   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11542
11543   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11544   // global base reg.
11545   unsigned char OpFlag = 0;
11546   unsigned WrapperKind = X86ISD::Wrapper;
11547   CodeModel::Model M = DAG.getTarget().getCodeModel();
11548
11549   if (Subtarget->isPICStyleRIPRel() &&
11550       (M == CodeModel::Small || M == CodeModel::Kernel))
11551     WrapperKind = X86ISD::WrapperRIP;
11552   else if (Subtarget->isPICStyleGOT())
11553     OpFlag = X86II::MO_GOTOFF;
11554   else if (Subtarget->isPICStyleStubPIC())
11555     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11556
11557   auto PtrVT = getPointerTy(DAG.getDataLayout());
11558   SDValue Result = DAG.getTargetConstantPool(
11559       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11560   SDLoc DL(CP);
11561   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11562   // With PIC, the address is actually $g + Offset.
11563   if (OpFlag) {
11564     Result =
11565         DAG.getNode(ISD::ADD, DL, PtrVT,
11566                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11567   }
11568
11569   return Result;
11570 }
11571
11572 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11573   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11574
11575   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11576   // global base reg.
11577   unsigned char OpFlag = 0;
11578   unsigned WrapperKind = X86ISD::Wrapper;
11579   CodeModel::Model M = DAG.getTarget().getCodeModel();
11580
11581   if (Subtarget->isPICStyleRIPRel() &&
11582       (M == CodeModel::Small || M == CodeModel::Kernel))
11583     WrapperKind = X86ISD::WrapperRIP;
11584   else if (Subtarget->isPICStyleGOT())
11585     OpFlag = X86II::MO_GOTOFF;
11586   else if (Subtarget->isPICStyleStubPIC())
11587     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11588
11589   auto PtrVT = getPointerTy(DAG.getDataLayout());
11590   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11591   SDLoc DL(JT);
11592   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11593
11594   // With PIC, the address is actually $g + Offset.
11595   if (OpFlag)
11596     Result =
11597         DAG.getNode(ISD::ADD, DL, PtrVT,
11598                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11599
11600   return Result;
11601 }
11602
11603 SDValue
11604 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11605   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11606
11607   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11608   // global base reg.
11609   unsigned char OpFlag = 0;
11610   unsigned WrapperKind = X86ISD::Wrapper;
11611   CodeModel::Model M = DAG.getTarget().getCodeModel();
11612
11613   if (Subtarget->isPICStyleRIPRel() &&
11614       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11615     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11616       OpFlag = X86II::MO_GOTPCREL;
11617     WrapperKind = X86ISD::WrapperRIP;
11618   } else if (Subtarget->isPICStyleGOT()) {
11619     OpFlag = X86II::MO_GOT;
11620   } else if (Subtarget->isPICStyleStubPIC()) {
11621     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11622   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11623     OpFlag = X86II::MO_DARWIN_NONLAZY;
11624   }
11625
11626   auto PtrVT = getPointerTy(DAG.getDataLayout());
11627   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11628
11629   SDLoc DL(Op);
11630   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11631
11632   // With PIC, the address is actually $g + Offset.
11633   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11634       !Subtarget->is64Bit()) {
11635     Result =
11636         DAG.getNode(ISD::ADD, DL, PtrVT,
11637                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11638   }
11639
11640   // For symbols that require a load from a stub to get the address, emit the
11641   // load.
11642   if (isGlobalStubReference(OpFlag))
11643     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11644                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11645                          false, false, false, 0);
11646
11647   return Result;
11648 }
11649
11650 SDValue
11651 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11652   // Create the TargetBlockAddressAddress node.
11653   unsigned char OpFlags =
11654     Subtarget->ClassifyBlockAddressReference();
11655   CodeModel::Model M = DAG.getTarget().getCodeModel();
11656   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11657   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11658   SDLoc dl(Op);
11659   auto PtrVT = getPointerTy(DAG.getDataLayout());
11660   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11661
11662   if (Subtarget->isPICStyleRIPRel() &&
11663       (M == CodeModel::Small || M == CodeModel::Kernel))
11664     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11665   else
11666     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11667
11668   // With PIC, the address is actually $g + Offset.
11669   if (isGlobalRelativeToPICBase(OpFlags)) {
11670     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11671                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11672   }
11673
11674   return Result;
11675 }
11676
11677 SDValue
11678 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11679                                       int64_t Offset, SelectionDAG &DAG) const {
11680   // Create the TargetGlobalAddress node, folding in the constant
11681   // offset if it is legal.
11682   unsigned char OpFlags =
11683       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11684   CodeModel::Model M = DAG.getTarget().getCodeModel();
11685   auto PtrVT = getPointerTy(DAG.getDataLayout());
11686   SDValue Result;
11687   if (OpFlags == X86II::MO_NO_FLAG &&
11688       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11689     // A direct static reference to a global.
11690     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11691     Offset = 0;
11692   } else {
11693     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11694   }
11695
11696   if (Subtarget->isPICStyleRIPRel() &&
11697       (M == CodeModel::Small || M == CodeModel::Kernel))
11698     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11699   else
11700     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11701
11702   // With PIC, the address is actually $g + Offset.
11703   if (isGlobalRelativeToPICBase(OpFlags)) {
11704     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11705                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11706   }
11707
11708   // For globals that require a load from a stub to get the address, emit the
11709   // load.
11710   if (isGlobalStubReference(OpFlags))
11711     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11712                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11713                          false, false, false, 0);
11714
11715   // If there was a non-zero offset that we didn't fold, create an explicit
11716   // addition for it.
11717   if (Offset != 0)
11718     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11719                          DAG.getConstant(Offset, dl, PtrVT));
11720
11721   return Result;
11722 }
11723
11724 SDValue
11725 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11726   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11727   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11728   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11729 }
11730
11731 static SDValue
11732 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11733            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11734            unsigned char OperandFlags, bool LocalDynamic = false) {
11735   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11736   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11737   SDLoc dl(GA);
11738   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11739                                            GA->getValueType(0),
11740                                            GA->getOffset(),
11741                                            OperandFlags);
11742
11743   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11744                                            : X86ISD::TLSADDR;
11745
11746   if (InFlag) {
11747     SDValue Ops[] = { Chain,  TGA, *InFlag };
11748     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11749   } else {
11750     SDValue Ops[]  = { Chain, TGA };
11751     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11752   }
11753
11754   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11755   MFI->setAdjustsStack(true);
11756   MFI->setHasCalls(true);
11757
11758   SDValue Flag = Chain.getValue(1);
11759   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11760 }
11761
11762 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11763 static SDValue
11764 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11765                                 const EVT PtrVT) {
11766   SDValue InFlag;
11767   SDLoc dl(GA);  // ? function entry point might be better
11768   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11769                                    DAG.getNode(X86ISD::GlobalBaseReg,
11770                                                SDLoc(), PtrVT), InFlag);
11771   InFlag = Chain.getValue(1);
11772
11773   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11774 }
11775
11776 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11777 static SDValue
11778 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11779                                 const EVT PtrVT) {
11780   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11781                     X86::RAX, X86II::MO_TLSGD);
11782 }
11783
11784 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11785                                            SelectionDAG &DAG,
11786                                            const EVT PtrVT,
11787                                            bool is64Bit) {
11788   SDLoc dl(GA);
11789
11790   // Get the start address of the TLS block for this module.
11791   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11792       .getInfo<X86MachineFunctionInfo>();
11793   MFI->incNumLocalDynamicTLSAccesses();
11794
11795   SDValue Base;
11796   if (is64Bit) {
11797     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11798                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11799   } else {
11800     SDValue InFlag;
11801     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11802         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11803     InFlag = Chain.getValue(1);
11804     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11805                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11806   }
11807
11808   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11809   // of Base.
11810
11811   // Build x@dtpoff.
11812   unsigned char OperandFlags = X86II::MO_DTPOFF;
11813   unsigned WrapperKind = X86ISD::Wrapper;
11814   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11815                                            GA->getValueType(0),
11816                                            GA->getOffset(), OperandFlags);
11817   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11818
11819   // Add x@dtpoff with the base.
11820   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11821 }
11822
11823 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11824 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11825                                    const EVT PtrVT, TLSModel::Model model,
11826                                    bool is64Bit, bool isPIC) {
11827   SDLoc dl(GA);
11828
11829   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11830   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11831                                                          is64Bit ? 257 : 256));
11832
11833   SDValue ThreadPointer =
11834       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11835                   MachinePointerInfo(Ptr), false, false, false, 0);
11836
11837   unsigned char OperandFlags = 0;
11838   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11839   // initialexec.
11840   unsigned WrapperKind = X86ISD::Wrapper;
11841   if (model == TLSModel::LocalExec) {
11842     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11843   } else if (model == TLSModel::InitialExec) {
11844     if (is64Bit) {
11845       OperandFlags = X86II::MO_GOTTPOFF;
11846       WrapperKind = X86ISD::WrapperRIP;
11847     } else {
11848       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11849     }
11850   } else {
11851     llvm_unreachable("Unexpected model");
11852   }
11853
11854   // emit "addl x@ntpoff,%eax" (local exec)
11855   // or "addl x@indntpoff,%eax" (initial exec)
11856   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11857   SDValue TGA =
11858       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11859                                  GA->getOffset(), OperandFlags);
11860   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11861
11862   if (model == TLSModel::InitialExec) {
11863     if (isPIC && !is64Bit) {
11864       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11865                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11866                            Offset);
11867     }
11868
11869     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11870                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11871                          false, false, false, 0);
11872   }
11873
11874   // The address of the thread local variable is the add of the thread
11875   // pointer with the offset of the variable.
11876   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11877 }
11878
11879 SDValue
11880 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11881
11882   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11883   const GlobalValue *GV = GA->getGlobal();
11884   auto PtrVT = getPointerTy(DAG.getDataLayout());
11885
11886   if (Subtarget->isTargetELF()) {
11887     if (DAG.getTarget().Options.EmulatedTLS)
11888       return LowerToTLSEmulatedModel(GA, DAG);
11889     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11890     switch (model) {
11891       case TLSModel::GeneralDynamic:
11892         if (Subtarget->is64Bit())
11893           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11894         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11895       case TLSModel::LocalDynamic:
11896         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11897                                            Subtarget->is64Bit());
11898       case TLSModel::InitialExec:
11899       case TLSModel::LocalExec:
11900         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11901                                    DAG.getTarget().getRelocationModel() ==
11902                                        Reloc::PIC_);
11903     }
11904     llvm_unreachable("Unknown TLS model.");
11905   }
11906
11907   if (Subtarget->isTargetDarwin()) {
11908     // Darwin only has one model of TLS.  Lower to that.
11909     unsigned char OpFlag = 0;
11910     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11911                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11912
11913     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11914     // global base reg.
11915     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11916                  !Subtarget->is64Bit();
11917     if (PIC32)
11918       OpFlag = X86II::MO_TLVP_PIC_BASE;
11919     else
11920       OpFlag = X86II::MO_TLVP;
11921     SDLoc DL(Op);
11922     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11923                                                 GA->getValueType(0),
11924                                                 GA->getOffset(), OpFlag);
11925     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11926
11927     // With PIC32, the address is actually $g + Offset.
11928     if (PIC32)
11929       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11930                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11931                            Offset);
11932
11933     // Lowering the machine isd will make sure everything is in the right
11934     // location.
11935     SDValue Chain = DAG.getEntryNode();
11936     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11937     SDValue Args[] = { Chain, Offset };
11938     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11939
11940     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11941     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11942     MFI->setAdjustsStack(true);
11943
11944     // And our return value (tls address) is in the standard call return value
11945     // location.
11946     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11947     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11948   }
11949
11950   if (Subtarget->isTargetKnownWindowsMSVC() ||
11951       Subtarget->isTargetWindowsGNU()) {
11952     // Just use the implicit TLS architecture
11953     // Need to generate someting similar to:
11954     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11955     //                                  ; from TEB
11956     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11957     //   mov     rcx, qword [rdx+rcx*8]
11958     //   mov     eax, .tls$:tlsvar
11959     //   [rax+rcx] contains the address
11960     // Windows 64bit: gs:0x58
11961     // Windows 32bit: fs:__tls_array
11962
11963     SDLoc dl(GA);
11964     SDValue Chain = DAG.getEntryNode();
11965
11966     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11967     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11968     // use its literal value of 0x2C.
11969     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11970                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11971                                                              256)
11972                                         : Type::getInt32PtrTy(*DAG.getContext(),
11973                                                               257));
11974
11975     SDValue TlsArray = Subtarget->is64Bit()
11976                            ? DAG.getIntPtrConstant(0x58, dl)
11977                            : (Subtarget->isTargetWindowsGNU()
11978                                   ? DAG.getIntPtrConstant(0x2C, dl)
11979                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11980
11981     SDValue ThreadPointer =
11982         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11983                     false, false, 0);
11984
11985     SDValue res;
11986     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11987       res = ThreadPointer;
11988     } else {
11989       // Load the _tls_index variable
11990       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11991       if (Subtarget->is64Bit())
11992         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11993                              MachinePointerInfo(), MVT::i32, false, false,
11994                              false, 0);
11995       else
11996         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11997                           false, false, 0);
11998
11999       auto &DL = DAG.getDataLayout();
12000       SDValue Scale =
12001           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12002       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12003
12004       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12005     }
12006
12007     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12008                       false, 0);
12009
12010     // Get the offset of start of .tls section
12011     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12012                                              GA->getValueType(0),
12013                                              GA->getOffset(), X86II::MO_SECREL);
12014     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12015
12016     // The address of the thread local variable is the add of the thread
12017     // pointer with the offset of the variable.
12018     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12019   }
12020
12021   llvm_unreachable("TLS not implemented for this target.");
12022 }
12023
12024 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12025 /// and take a 2 x i32 value to shift plus a shift amount.
12026 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12027   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12028   MVT VT = Op.getSimpleValueType();
12029   unsigned VTBits = VT.getSizeInBits();
12030   SDLoc dl(Op);
12031   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12032   SDValue ShOpLo = Op.getOperand(0);
12033   SDValue ShOpHi = Op.getOperand(1);
12034   SDValue ShAmt  = Op.getOperand(2);
12035   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12036   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12037   // during isel.
12038   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12039                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12040   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12041                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12042                        : DAG.getConstant(0, dl, VT);
12043
12044   SDValue Tmp2, Tmp3;
12045   if (Op.getOpcode() == ISD::SHL_PARTS) {
12046     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12047     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12048   } else {
12049     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12050     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12051   }
12052
12053   // If the shift amount is larger or equal than the width of a part we can't
12054   // rely on the results of shld/shrd. Insert a test and select the appropriate
12055   // values for large shift amounts.
12056   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12057                                 DAG.getConstant(VTBits, dl, MVT::i8));
12058   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12059                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12060
12061   SDValue Hi, Lo;
12062   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12063   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12064   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12065
12066   if (Op.getOpcode() == ISD::SHL_PARTS) {
12067     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12068     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12069   } else {
12070     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12071     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12072   }
12073
12074   SDValue Ops[2] = { Lo, Hi };
12075   return DAG.getMergeValues(Ops, dl);
12076 }
12077
12078 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12079                                            SelectionDAG &DAG) const {
12080   SDValue Src = Op.getOperand(0);
12081   MVT SrcVT = Src.getSimpleValueType();
12082   MVT VT = Op.getSimpleValueType();
12083   SDLoc dl(Op);
12084
12085   if (SrcVT.isVector()) {
12086     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12087       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12088                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12089                          DAG.getUNDEF(SrcVT)));
12090     }
12091     if (SrcVT.getVectorElementType() == MVT::i1) {
12092       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12093       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12094                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12095     }
12096     return SDValue();
12097   }
12098
12099   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12100          "Unknown SINT_TO_FP to lower!");
12101
12102   // These are really Legal; return the operand so the caller accepts it as
12103   // Legal.
12104   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12105     return Op;
12106   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12107       Subtarget->is64Bit()) {
12108     return Op;
12109   }
12110
12111   unsigned Size = SrcVT.getSizeInBits()/8;
12112   MachineFunction &MF = DAG.getMachineFunction();
12113   auto PtrVT = getPointerTy(MF.getDataLayout());
12114   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12115   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12116   SDValue Chain = DAG.getStore(
12117       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12118       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12119       false, 0);
12120   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12121 }
12122
12123 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12124                                      SDValue StackSlot,
12125                                      SelectionDAG &DAG) const {
12126   // Build the FILD
12127   SDLoc DL(Op);
12128   SDVTList Tys;
12129   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12130   if (useSSE)
12131     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12132   else
12133     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12134
12135   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12136
12137   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12138   MachineMemOperand *MMO;
12139   if (FI) {
12140     int SSFI = FI->getIndex();
12141     MMO = DAG.getMachineFunction().getMachineMemOperand(
12142         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12143         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12144   } else {
12145     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12146     StackSlot = StackSlot.getOperand(1);
12147   }
12148   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12149   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12150                                            X86ISD::FILD, DL,
12151                                            Tys, Ops, SrcVT, MMO);
12152
12153   if (useSSE) {
12154     Chain = Result.getValue(1);
12155     SDValue InFlag = Result.getValue(2);
12156
12157     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12158     // shouldn't be necessary except that RFP cannot be live across
12159     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12160     MachineFunction &MF = DAG.getMachineFunction();
12161     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12162     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12163     auto PtrVT = getPointerTy(MF.getDataLayout());
12164     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12165     Tys = DAG.getVTList(MVT::Other);
12166     SDValue Ops[] = {
12167       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12168     };
12169     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12170         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12171         MachineMemOperand::MOStore, SSFISize, SSFISize);
12172
12173     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12174                                     Ops, Op.getValueType(), MMO);
12175     Result = DAG.getLoad(
12176         Op.getValueType(), DL, Chain, StackSlot,
12177         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12178         false, false, false, 0);
12179   }
12180
12181   return Result;
12182 }
12183
12184 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12185 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12186                                                SelectionDAG &DAG) const {
12187   // This algorithm is not obvious. Here it is what we're trying to output:
12188   /*
12189      movq       %rax,  %xmm0
12190      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12191      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12192      #ifdef __SSE3__
12193        haddpd   %xmm0, %xmm0
12194      #else
12195        pshufd   $0x4e, %xmm0, %xmm1
12196        addpd    %xmm1, %xmm0
12197      #endif
12198   */
12199
12200   SDLoc dl(Op);
12201   LLVMContext *Context = DAG.getContext();
12202
12203   // Build some magic constants.
12204   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12205   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12206   auto PtrVT = getPointerTy(DAG.getDataLayout());
12207   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12208
12209   SmallVector<Constant*,2> CV1;
12210   CV1.push_back(
12211     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12212                                       APInt(64, 0x4330000000000000ULL))));
12213   CV1.push_back(
12214     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12215                                       APInt(64, 0x4530000000000000ULL))));
12216   Constant *C1 = ConstantVector::get(CV1);
12217   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12218
12219   // Load the 64-bit value into an XMM register.
12220   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12221                             Op.getOperand(0));
12222   SDValue CLod0 =
12223       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12224                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12225                   false, false, false, 16);
12226   SDValue Unpck1 =
12227       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12228
12229   SDValue CLod1 =
12230       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12231                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12232                   false, false, false, 16);
12233   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12234   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12235   SDValue Result;
12236
12237   if (Subtarget->hasSSE3()) {
12238     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12239     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12240   } else {
12241     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12242     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12243                                            S2F, 0x4E, DAG);
12244     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12245                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12246   }
12247
12248   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12249                      DAG.getIntPtrConstant(0, dl));
12250 }
12251
12252 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12253 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12254                                                SelectionDAG &DAG) const {
12255   SDLoc dl(Op);
12256   // FP constant to bias correct the final result.
12257   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12258                                    MVT::f64);
12259
12260   // Load the 32-bit value into an XMM register.
12261   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12262                              Op.getOperand(0));
12263
12264   // Zero out the upper parts of the register.
12265   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12266
12267   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12268                      DAG.getBitcast(MVT::v2f64, Load),
12269                      DAG.getIntPtrConstant(0, dl));
12270
12271   // Or the load with the bias.
12272   SDValue Or = DAG.getNode(
12273       ISD::OR, dl, MVT::v2i64,
12274       DAG.getBitcast(MVT::v2i64,
12275                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12276       DAG.getBitcast(MVT::v2i64,
12277                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12278   Or =
12279       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12280                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12281
12282   // Subtract the bias.
12283   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12284
12285   // Handle final rounding.
12286   EVT DestVT = Op.getValueType();
12287
12288   if (DestVT.bitsLT(MVT::f64))
12289     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12290                        DAG.getIntPtrConstant(0, dl));
12291   if (DestVT.bitsGT(MVT::f64))
12292     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12293
12294   // Handle final rounding.
12295   return Sub;
12296 }
12297
12298 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12299                                      const X86Subtarget &Subtarget) {
12300   // The algorithm is the following:
12301   // #ifdef __SSE4_1__
12302   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12303   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12304   //                                 (uint4) 0x53000000, 0xaa);
12305   // #else
12306   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12307   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12308   // #endif
12309   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12310   //     return (float4) lo + fhi;
12311
12312   SDLoc DL(Op);
12313   SDValue V = Op->getOperand(0);
12314   EVT VecIntVT = V.getValueType();
12315   bool Is128 = VecIntVT == MVT::v4i32;
12316   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12317   // If we convert to something else than the supported type, e.g., to v4f64,
12318   // abort early.
12319   if (VecFloatVT != Op->getValueType(0))
12320     return SDValue();
12321
12322   unsigned NumElts = VecIntVT.getVectorNumElements();
12323   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12324          "Unsupported custom type");
12325   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12326
12327   // In the #idef/#else code, we have in common:
12328   // - The vector of constants:
12329   // -- 0x4b000000
12330   // -- 0x53000000
12331   // - A shift:
12332   // -- v >> 16
12333
12334   // Create the splat vector for 0x4b000000.
12335   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12336   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12337                            CstLow, CstLow, CstLow, CstLow};
12338   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12339                                   makeArrayRef(&CstLowArray[0], NumElts));
12340   // Create the splat vector for 0x53000000.
12341   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12342   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12343                             CstHigh, CstHigh, CstHigh, CstHigh};
12344   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12345                                    makeArrayRef(&CstHighArray[0], NumElts));
12346
12347   // Create the right shift.
12348   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12349   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12350                              CstShift, CstShift, CstShift, CstShift};
12351   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12352                                     makeArrayRef(&CstShiftArray[0], NumElts));
12353   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12354
12355   SDValue Low, High;
12356   if (Subtarget.hasSSE41()) {
12357     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12358     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12359     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12360     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12361     // Low will be bitcasted right away, so do not bother bitcasting back to its
12362     // original type.
12363     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12364                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12365     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12366     //                                 (uint4) 0x53000000, 0xaa);
12367     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12368     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12369     // High will be bitcasted right away, so do not bother bitcasting back to
12370     // its original type.
12371     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12372                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12373   } else {
12374     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12375     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12376                                      CstMask, CstMask, CstMask);
12377     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12378     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12379     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12380
12381     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12382     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12383   }
12384
12385   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12386   SDValue CstFAdd = DAG.getConstantFP(
12387       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12388   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12389                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12390   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12391                                    makeArrayRef(&CstFAddArray[0], NumElts));
12392
12393   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12394   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12395   SDValue FHigh =
12396       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12397   //     return (float4) lo + fhi;
12398   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12399   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12400 }
12401
12402 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12403                                                SelectionDAG &DAG) const {
12404   SDValue N0 = Op.getOperand(0);
12405   MVT SVT = N0.getSimpleValueType();
12406   SDLoc dl(Op);
12407
12408   switch (SVT.SimpleTy) {
12409   default:
12410     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12411   case MVT::v4i8:
12412   case MVT::v4i16:
12413   case MVT::v8i8:
12414   case MVT::v8i16: {
12415     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12416     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12417                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12418   }
12419   case MVT::v4i32:
12420   case MVT::v8i32:
12421     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12422   case MVT::v16i8:
12423   case MVT::v16i16:
12424     if (Subtarget->hasAVX512())
12425       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12426                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12427   }
12428   llvm_unreachable(nullptr);
12429 }
12430
12431 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12432                                            SelectionDAG &DAG) const {
12433   SDValue N0 = Op.getOperand(0);
12434   SDLoc dl(Op);
12435   auto PtrVT = getPointerTy(DAG.getDataLayout());
12436
12437   if (Op.getValueType().isVector())
12438     return lowerUINT_TO_FP_vec(Op, DAG);
12439
12440   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12441   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12442   // the optimization here.
12443   if (DAG.SignBitIsZero(N0))
12444     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12445
12446   MVT SrcVT = N0.getSimpleValueType();
12447   MVT DstVT = Op.getSimpleValueType();
12448   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12449     return LowerUINT_TO_FP_i64(Op, DAG);
12450   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12451     return LowerUINT_TO_FP_i32(Op, DAG);
12452   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12453     return SDValue();
12454
12455   // Make a 64-bit buffer, and use it to build an FILD.
12456   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12457   if (SrcVT == MVT::i32) {
12458     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12459     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12460     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12461                                   StackSlot, MachinePointerInfo(),
12462                                   false, false, 0);
12463     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12464                                   OffsetSlot, MachinePointerInfo(),
12465                                   false, false, 0);
12466     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12467     return Fild;
12468   }
12469
12470   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12471   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12472                                StackSlot, MachinePointerInfo(),
12473                                false, false, 0);
12474   // For i64 source, we need to add the appropriate power of 2 if the input
12475   // was negative.  This is the same as the optimization in
12476   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12477   // we must be careful to do the computation in x87 extended precision, not
12478   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12479   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12480   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12481       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12482       MachineMemOperand::MOLoad, 8, 8);
12483
12484   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12485   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12486   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12487                                          MVT::i64, MMO);
12488
12489   APInt FF(32, 0x5F800000ULL);
12490
12491   // Check whether the sign bit is set.
12492   SDValue SignSet = DAG.getSetCC(
12493       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12494       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12495
12496   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12497   SDValue FudgePtr = DAG.getConstantPool(
12498       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12499
12500   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12501   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12502   SDValue Four = DAG.getIntPtrConstant(4, dl);
12503   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12504                                Zero, Four);
12505   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12506
12507   // Load the value out, extending it from f32 to f80.
12508   // FIXME: Avoid the extend by constructing the right constant pool?
12509   SDValue Fudge = DAG.getExtLoad(
12510       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12511       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12512       false, false, false, 4);
12513   // Extend everything to 80 bits to force it to be done on x87.
12514   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12515   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12516                      DAG.getIntPtrConstant(0, dl));
12517 }
12518
12519 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12520 // is legal, or has an f16 source (which needs to be promoted to f32),
12521 // just return an <SDValue(), SDValue()> pair.
12522 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12523 // to i16, i32 or i64, and we lower it to a legal sequence.
12524 // If lowered to the final integer result we return a <result, SDValue()> pair.
12525 // Otherwise we lower it to a sequence ending with a FIST, return a
12526 // <FIST, StackSlot> pair, and the caller is responsible for loading
12527 // the final integer result from StackSlot.
12528 std::pair<SDValue,SDValue>
12529 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12530                                    bool IsSigned, bool IsReplace) const {
12531   SDLoc DL(Op);
12532
12533   EVT DstTy = Op.getValueType();
12534   EVT TheVT = Op.getOperand(0).getValueType();
12535   auto PtrVT = getPointerTy(DAG.getDataLayout());
12536
12537   if (TheVT == MVT::f16)
12538     // We need to promote the f16 to f32 before using the lowering
12539     // in this routine.
12540     return std::make_pair(SDValue(), SDValue());
12541
12542   assert((TheVT == MVT::f32 ||
12543           TheVT == MVT::f64 ||
12544           TheVT == MVT::f80) &&
12545          "Unexpected FP operand type in FP_TO_INTHelper");
12546
12547   // If using FIST to compute an unsigned i64, we'll need some fixup
12548   // to handle values above the maximum signed i64.  A FIST is always
12549   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12550   bool UnsignedFixup = !IsSigned &&
12551                        DstTy == MVT::i64 &&
12552                        (!Subtarget->is64Bit() ||
12553                         !isScalarFPTypeInSSEReg(TheVT));
12554
12555   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12556     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12557     // The low 32 bits of the fist result will have the correct uint32 result.
12558     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12559     DstTy = MVT::i64;
12560   }
12561
12562   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12563          DstTy.getSimpleVT() >= MVT::i16 &&
12564          "Unknown FP_TO_INT to lower!");
12565
12566   // These are really Legal.
12567   if (DstTy == MVT::i32 &&
12568       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12569     return std::make_pair(SDValue(), SDValue());
12570   if (Subtarget->is64Bit() &&
12571       DstTy == MVT::i64 &&
12572       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12573     return std::make_pair(SDValue(), SDValue());
12574
12575   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12576   // stack slot.
12577   MachineFunction &MF = DAG.getMachineFunction();
12578   unsigned MemSize = DstTy.getSizeInBits()/8;
12579   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12580   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12581
12582   unsigned Opc;
12583   switch (DstTy.getSimpleVT().SimpleTy) {
12584   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12585   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12586   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12587   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12588   }
12589
12590   SDValue Chain = DAG.getEntryNode();
12591   SDValue Value = Op.getOperand(0);
12592   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12593
12594   if (UnsignedFixup) {
12595     //
12596     // Conversion to unsigned i64 is implemented with a select,
12597     // depending on whether the source value fits in the range
12598     // of a signed i64.  Let Thresh be the FP equivalent of
12599     // 0x8000000000000000ULL.
12600     //
12601     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12602     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12603     //  Fist-to-mem64 FistSrc
12604     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12605     //  to XOR'ing the high 32 bits with Adjust.
12606     //
12607     // Being a power of 2, Thresh is exactly representable in all FP formats.
12608     // For X87 we'd like to use the smallest FP type for this constant, but
12609     // for DAG type consistency we have to match the FP operand type.
12610
12611     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12612     APFloat::opStatus Status = APFloat::opOK;
12613     bool LosesInfo = false;
12614     if (TheVT == MVT::f64)
12615       // The rounding mode is irrelevant as the conversion should be exact.
12616       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12617                               &LosesInfo);
12618     else if (TheVT == MVT::f80)
12619       Status = Thresh.convert(APFloat::x87DoubleExtended,
12620                               APFloat::rmNearestTiesToEven, &LosesInfo);
12621
12622     assert(Status == APFloat::opOK && !LosesInfo &&
12623            "FP conversion should have been exact");
12624
12625     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12626
12627     SDValue Cmp = DAG.getSetCC(DL,
12628                                getSetCCResultType(DAG.getDataLayout(),
12629                                                   *DAG.getContext(), TheVT),
12630                                Value, ThreshVal, ISD::SETLT);
12631     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12632                            DAG.getConstant(0, DL, MVT::i32),
12633                            DAG.getConstant(0x80000000, DL, MVT::i32));
12634     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12635     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12636                                               *DAG.getContext(), TheVT),
12637                        Value, ThreshVal, ISD::SETLT);
12638     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12639   }
12640
12641   // FIXME This causes a redundant load/store if the SSE-class value is already
12642   // in memory, such as if it is on the callstack.
12643   if (isScalarFPTypeInSSEReg(TheVT)) {
12644     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12645     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12646                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12647                          false, 0);
12648     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12649     SDValue Ops[] = {
12650       Chain, StackSlot, DAG.getValueType(TheVT)
12651     };
12652
12653     MachineMemOperand *MMO =
12654         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12655                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12656     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12657     Chain = Value.getValue(1);
12658     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12659     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12660   }
12661
12662   MachineMemOperand *MMO =
12663       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12664                               MachineMemOperand::MOStore, MemSize, MemSize);
12665
12666   if (UnsignedFixup) {
12667
12668     // Insert the FIST, load its result as two i32's,
12669     // and XOR the high i32 with Adjust.
12670
12671     SDValue FistOps[] = { Chain, Value, StackSlot };
12672     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12673                                            FistOps, DstTy, MMO);
12674
12675     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12676                                 MachinePointerInfo(),
12677                                 false, false, false, 0);
12678     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12679                                    DAG.getConstant(4, DL, PtrVT));
12680
12681     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12682                                  MachinePointerInfo(),
12683                                  false, false, false, 0);
12684     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12685
12686     if (Subtarget->is64Bit()) {
12687       // Join High32 and Low32 into a 64-bit result.
12688       // (High32 << 32) | Low32
12689       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12690       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12691       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12692                            DAG.getConstant(32, DL, MVT::i8));
12693       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12694       return std::make_pair(Result, SDValue());
12695     }
12696
12697     SDValue ResultOps[] = { Low32, High32 };
12698
12699     SDValue pair = IsReplace
12700       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12701       : DAG.getMergeValues(ResultOps, DL);
12702     return std::make_pair(pair, SDValue());
12703   } else {
12704     // Build the FP_TO_INT*_IN_MEM
12705     SDValue Ops[] = { Chain, Value, StackSlot };
12706     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12707                                            Ops, DstTy, MMO);
12708     return std::make_pair(FIST, StackSlot);
12709   }
12710 }
12711
12712 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12713                               const X86Subtarget *Subtarget) {
12714   MVT VT = Op->getSimpleValueType(0);
12715   SDValue In = Op->getOperand(0);
12716   MVT InVT = In.getSimpleValueType();
12717   SDLoc dl(Op);
12718
12719   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12720     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12721
12722   // Optimize vectors in AVX mode:
12723   //
12724   //   v8i16 -> v8i32
12725   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12726   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12727   //   Concat upper and lower parts.
12728   //
12729   //   v4i32 -> v4i64
12730   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12731   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12732   //   Concat upper and lower parts.
12733   //
12734
12735   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12736       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12737       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12738     return SDValue();
12739
12740   if (Subtarget->hasInt256())
12741     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12742
12743   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12744   SDValue Undef = DAG.getUNDEF(InVT);
12745   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12746   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12747   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12748
12749   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12750                              VT.getVectorNumElements()/2);
12751
12752   OpLo = DAG.getBitcast(HVT, OpLo);
12753   OpHi = DAG.getBitcast(HVT, OpHi);
12754
12755   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12756 }
12757
12758 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12759                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12760   MVT VT = Op->getSimpleValueType(0);
12761   SDValue In = Op->getOperand(0);
12762   MVT InVT = In.getSimpleValueType();
12763   SDLoc DL(Op);
12764   unsigned int NumElts = VT.getVectorNumElements();
12765   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12766     return SDValue();
12767
12768   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12769     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12770
12771   assert(InVT.getVectorElementType() == MVT::i1);
12772   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12773   SDValue One =
12774    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12775   SDValue Zero =
12776    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12777
12778   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12779   if (VT.is512BitVector())
12780     return V;
12781   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12782 }
12783
12784 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12785                                SelectionDAG &DAG) {
12786   if (Subtarget->hasFp256())
12787     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12788       return Res;
12789
12790   return SDValue();
12791 }
12792
12793 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12794                                 SelectionDAG &DAG) {
12795   SDLoc DL(Op);
12796   MVT VT = Op.getSimpleValueType();
12797   SDValue In = Op.getOperand(0);
12798   MVT SVT = In.getSimpleValueType();
12799
12800   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12801     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12802
12803   if (Subtarget->hasFp256())
12804     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12805       return Res;
12806
12807   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12808          VT.getVectorNumElements() != SVT.getVectorNumElements());
12809   return SDValue();
12810 }
12811
12812 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12813   SDLoc DL(Op);
12814   MVT VT = Op.getSimpleValueType();
12815   SDValue In = Op.getOperand(0);
12816   MVT InVT = In.getSimpleValueType();
12817
12818   if (VT == MVT::i1) {
12819     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12820            "Invalid scalar TRUNCATE operation");
12821     if (InVT.getSizeInBits() >= 32)
12822       return SDValue();
12823     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12824     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12825   }
12826   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12827          "Invalid TRUNCATE operation");
12828
12829   // move vector to mask - truncate solution for SKX
12830   if (VT.getVectorElementType() == MVT::i1) {
12831     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12832         Subtarget->hasBWI())
12833       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12834     if ((InVT.is256BitVector() || InVT.is128BitVector())
12835         && InVT.getScalarSizeInBits() <= 16 &&
12836         Subtarget->hasBWI() && Subtarget->hasVLX())
12837       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12838     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12839         Subtarget->hasDQI())
12840       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12841     if ((InVT.is256BitVector() || InVT.is128BitVector())
12842         && InVT.getScalarSizeInBits() >= 32 &&
12843         Subtarget->hasDQI() && Subtarget->hasVLX())
12844       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12845   }
12846
12847   if (VT.getVectorElementType() == MVT::i1) {
12848     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12849     unsigned NumElts = InVT.getVectorNumElements();
12850     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12851     if (InVT.getSizeInBits() < 512) {
12852       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12853       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12854       InVT = ExtVT;
12855     }
12856
12857     SDValue OneV =
12858      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12859     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12860     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12861   }
12862
12863   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12864   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12865       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12866     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12867
12868   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12869     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12870     if (Subtarget->hasInt256()) {
12871       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12872       In = DAG.getBitcast(MVT::v8i32, In);
12873       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12874                                 ShufMask);
12875       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12876                          DAG.getIntPtrConstant(0, DL));
12877     }
12878
12879     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12880                                DAG.getIntPtrConstant(0, DL));
12881     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12882                                DAG.getIntPtrConstant(2, DL));
12883     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12884     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12885     static const int ShufMask[] = {0, 2, 4, 6};
12886     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12887   }
12888
12889   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12890     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12891     if (Subtarget->hasInt256()) {
12892       In = DAG.getBitcast(MVT::v32i8, In);
12893
12894       SmallVector<SDValue,32> pshufbMask;
12895       for (unsigned i = 0; i < 2; ++i) {
12896         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12897         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12898         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12899         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12900         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12901         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12902         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12903         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12904         for (unsigned j = 0; j < 8; ++j)
12905           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12906       }
12907       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12908       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12909       In = DAG.getBitcast(MVT::v4i64, In);
12910
12911       static const int ShufMask[] = {0,  2,  -1,  -1};
12912       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12913                                 &ShufMask[0]);
12914       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12915                        DAG.getIntPtrConstant(0, DL));
12916       return DAG.getBitcast(VT, In);
12917     }
12918
12919     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12920                                DAG.getIntPtrConstant(0, DL));
12921
12922     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12923                                DAG.getIntPtrConstant(4, DL));
12924
12925     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12926     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12927
12928     // The PSHUFB mask:
12929     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12930                                    -1, -1, -1, -1, -1, -1, -1, -1};
12931
12932     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12933     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12934     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12935
12936     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12937     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12938
12939     // The MOVLHPS Mask:
12940     static const int ShufMask2[] = {0, 1, 4, 5};
12941     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12942     return DAG.getBitcast(MVT::v8i16, res);
12943   }
12944
12945   // Handle truncation of V256 to V128 using shuffles.
12946   if (!VT.is128BitVector() || !InVT.is256BitVector())
12947     return SDValue();
12948
12949   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12950
12951   unsigned NumElems = VT.getVectorNumElements();
12952   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12953
12954   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12955   // Prepare truncation shuffle mask
12956   for (unsigned i = 0; i != NumElems; ++i)
12957     MaskVec[i] = i * 2;
12958   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12959                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12960   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12961                      DAG.getIntPtrConstant(0, DL));
12962 }
12963
12964 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12965                                            SelectionDAG &DAG) const {
12966   assert(!Op.getSimpleValueType().isVector());
12967
12968   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12969     /*IsSigned=*/ true, /*IsReplace=*/ false);
12970   SDValue FIST = Vals.first, StackSlot = Vals.second;
12971   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12972   if (!FIST.getNode())
12973     return Op;
12974
12975   if (StackSlot.getNode())
12976     // Load the result.
12977     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12978                        FIST, StackSlot, MachinePointerInfo(),
12979                        false, false, false, 0);
12980
12981   // The node is the result.
12982   return FIST;
12983 }
12984
12985 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12986                                            SelectionDAG &DAG) const {
12987   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12988     /*IsSigned=*/ false, /*IsReplace=*/ false);
12989   SDValue FIST = Vals.first, StackSlot = Vals.second;
12990   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12991   if (!FIST.getNode())
12992     return Op;
12993
12994   if (StackSlot.getNode())
12995     // Load the result.
12996     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12997                        FIST, StackSlot, MachinePointerInfo(),
12998                        false, false, false, 0);
12999
13000   // The node is the result.
13001   return FIST;
13002 }
13003
13004 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13005   SDLoc DL(Op);
13006   MVT VT = Op.getSimpleValueType();
13007   SDValue In = Op.getOperand(0);
13008   MVT SVT = In.getSimpleValueType();
13009
13010   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13011
13012   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13013                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13014                                  In, DAG.getUNDEF(SVT)));
13015 }
13016
13017 /// The only differences between FABS and FNEG are the mask and the logic op.
13018 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13019 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13020   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13021          "Wrong opcode for lowering FABS or FNEG.");
13022
13023   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13024
13025   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13026   // into an FNABS. We'll lower the FABS after that if it is still in use.
13027   if (IsFABS)
13028     for (SDNode *User : Op->uses())
13029       if (User->getOpcode() == ISD::FNEG)
13030         return Op;
13031
13032   SDLoc dl(Op);
13033   MVT VT = Op.getSimpleValueType();
13034
13035   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13036   // decide if we should generate a 16-byte constant mask when we only need 4 or
13037   // 8 bytes for the scalar case.
13038
13039   MVT LogicVT;
13040   MVT EltVT;
13041   unsigned NumElts;
13042
13043   if (VT.isVector()) {
13044     LogicVT = VT;
13045     EltVT = VT.getVectorElementType();
13046     NumElts = VT.getVectorNumElements();
13047   } else {
13048     // There are no scalar bitwise logical SSE/AVX instructions, so we
13049     // generate a 16-byte vector constant and logic op even for the scalar case.
13050     // Using a 16-byte mask allows folding the load of the mask with
13051     // the logic op, so it can save (~4 bytes) on code size.
13052     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13053     EltVT = VT;
13054     NumElts = (VT == MVT::f64) ? 2 : 4;
13055   }
13056
13057   unsigned EltBits = EltVT.getSizeInBits();
13058   LLVMContext *Context = DAG.getContext();
13059   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13060   APInt MaskElt =
13061     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13062   Constant *C = ConstantInt::get(*Context, MaskElt);
13063   C = ConstantVector::getSplat(NumElts, C);
13064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13065   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13066   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13067   SDValue Mask =
13068       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13069                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13070                   false, false, false, Alignment);
13071
13072   SDValue Op0 = Op.getOperand(0);
13073   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13074   unsigned LogicOp =
13075     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13076   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13077
13078   if (VT.isVector())
13079     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13080
13081   // For the scalar case extend to a 128-bit vector, perform the logic op,
13082   // and extract the scalar result back out.
13083   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13084   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13085   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13086                      DAG.getIntPtrConstant(0, dl));
13087 }
13088
13089 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13090   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13091   LLVMContext *Context = DAG.getContext();
13092   SDValue Op0 = Op.getOperand(0);
13093   SDValue Op1 = Op.getOperand(1);
13094   SDLoc dl(Op);
13095   MVT VT = Op.getSimpleValueType();
13096   MVT SrcVT = Op1.getSimpleValueType();
13097
13098   // If second operand is smaller, extend it first.
13099   if (SrcVT.bitsLT(VT)) {
13100     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13101     SrcVT = VT;
13102   }
13103   // And if it is bigger, shrink it first.
13104   if (SrcVT.bitsGT(VT)) {
13105     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13106     SrcVT = VT;
13107   }
13108
13109   // At this point the operands and the result should have the same
13110   // type, and that won't be f80 since that is not custom lowered.
13111
13112   const fltSemantics &Sem =
13113       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13114   const unsigned SizeInBits = VT.getSizeInBits();
13115
13116   SmallVector<Constant *, 4> CV(
13117       VT == MVT::f64 ? 2 : 4,
13118       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13119
13120   // First, clear all bits but the sign bit from the second operand (sign).
13121   CV[0] = ConstantFP::get(*Context,
13122                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13123   Constant *C = ConstantVector::get(CV);
13124   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13125   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13126
13127   // Perform all logic operations as 16-byte vectors because there are no
13128   // scalar FP logic instructions in SSE. This allows load folding of the
13129   // constants into the logic instructions.
13130   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13131   SDValue Mask1 =
13132       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13133                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13134                   false, false, false, 16);
13135   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13136   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13137
13138   // Next, clear the sign bit from the first operand (magnitude).
13139   // If it's a constant, we can clear it here.
13140   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13141     APFloat APF = Op0CN->getValueAPF();
13142     // If the magnitude is a positive zero, the sign bit alone is enough.
13143     if (APF.isPosZero())
13144       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13145                          DAG.getIntPtrConstant(0, dl));
13146     APF.clearSign();
13147     CV[0] = ConstantFP::get(*Context, APF);
13148   } else {
13149     CV[0] = ConstantFP::get(
13150         *Context,
13151         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13152   }
13153   C = ConstantVector::get(CV);
13154   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13155   SDValue Val =
13156       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13157                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13158                   false, false, false, 16);
13159   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13160   if (!isa<ConstantFPSDNode>(Op0)) {
13161     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13162     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13163   }
13164   // OR the magnitude value with the sign bit.
13165   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13166   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13167                      DAG.getIntPtrConstant(0, dl));
13168 }
13169
13170 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13171   SDValue N0 = Op.getOperand(0);
13172   SDLoc dl(Op);
13173   MVT VT = Op.getSimpleValueType();
13174
13175   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13176   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13177                                   DAG.getConstant(1, dl, VT));
13178   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13179 }
13180
13181 // Check whether an OR'd tree is PTEST-able.
13182 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13183                                       SelectionDAG &DAG) {
13184   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13185
13186   if (!Subtarget->hasSSE41())
13187     return SDValue();
13188
13189   if (!Op->hasOneUse())
13190     return SDValue();
13191
13192   SDNode *N = Op.getNode();
13193   SDLoc DL(N);
13194
13195   SmallVector<SDValue, 8> Opnds;
13196   DenseMap<SDValue, unsigned> VecInMap;
13197   SmallVector<SDValue, 8> VecIns;
13198   EVT VT = MVT::Other;
13199
13200   // Recognize a special case where a vector is casted into wide integer to
13201   // test all 0s.
13202   Opnds.push_back(N->getOperand(0));
13203   Opnds.push_back(N->getOperand(1));
13204
13205   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13206     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13207     // BFS traverse all OR'd operands.
13208     if (I->getOpcode() == ISD::OR) {
13209       Opnds.push_back(I->getOperand(0));
13210       Opnds.push_back(I->getOperand(1));
13211       // Re-evaluate the number of nodes to be traversed.
13212       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13213       continue;
13214     }
13215
13216     // Quit if a non-EXTRACT_VECTOR_ELT
13217     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13218       return SDValue();
13219
13220     // Quit if without a constant index.
13221     SDValue Idx = I->getOperand(1);
13222     if (!isa<ConstantSDNode>(Idx))
13223       return SDValue();
13224
13225     SDValue ExtractedFromVec = I->getOperand(0);
13226     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13227     if (M == VecInMap.end()) {
13228       VT = ExtractedFromVec.getValueType();
13229       // Quit if not 128/256-bit vector.
13230       if (!VT.is128BitVector() && !VT.is256BitVector())
13231         return SDValue();
13232       // Quit if not the same type.
13233       if (VecInMap.begin() != VecInMap.end() &&
13234           VT != VecInMap.begin()->first.getValueType())
13235         return SDValue();
13236       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13237       VecIns.push_back(ExtractedFromVec);
13238     }
13239     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13240   }
13241
13242   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13243          "Not extracted from 128-/256-bit vector.");
13244
13245   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13246
13247   for (DenseMap<SDValue, unsigned>::const_iterator
13248         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13249     // Quit if not all elements are used.
13250     if (I->second != FullMask)
13251       return SDValue();
13252   }
13253
13254   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13255
13256   // Cast all vectors into TestVT for PTEST.
13257   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13258     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13259
13260   // If more than one full vectors are evaluated, OR them first before PTEST.
13261   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13262     // Each iteration will OR 2 nodes and append the result until there is only
13263     // 1 node left, i.e. the final OR'd value of all vectors.
13264     SDValue LHS = VecIns[Slot];
13265     SDValue RHS = VecIns[Slot + 1];
13266     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13267   }
13268
13269   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13270                      VecIns.back(), VecIns.back());
13271 }
13272
13273 /// \brief return true if \c Op has a use that doesn't just read flags.
13274 static bool hasNonFlagsUse(SDValue Op) {
13275   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13276        ++UI) {
13277     SDNode *User = *UI;
13278     unsigned UOpNo = UI.getOperandNo();
13279     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13280       // Look pass truncate.
13281       UOpNo = User->use_begin().getOperandNo();
13282       User = *User->use_begin();
13283     }
13284
13285     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13286         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13287       return true;
13288   }
13289   return false;
13290 }
13291
13292 /// Emit nodes that will be selected as "test Op0,Op0", or something
13293 /// equivalent.
13294 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13295                                     SelectionDAG &DAG) const {
13296   if (Op.getValueType() == MVT::i1) {
13297     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13298     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13299                        DAG.getConstant(0, dl, MVT::i8));
13300   }
13301   // CF and OF aren't always set the way we want. Determine which
13302   // of these we need.
13303   bool NeedCF = false;
13304   bool NeedOF = false;
13305   switch (X86CC) {
13306   default: break;
13307   case X86::COND_A: case X86::COND_AE:
13308   case X86::COND_B: case X86::COND_BE:
13309     NeedCF = true;
13310     break;
13311   case X86::COND_G: case X86::COND_GE:
13312   case X86::COND_L: case X86::COND_LE:
13313   case X86::COND_O: case X86::COND_NO: {
13314     // Check if we really need to set the
13315     // Overflow flag. If NoSignedWrap is present
13316     // that is not actually needed.
13317     switch (Op->getOpcode()) {
13318     case ISD::ADD:
13319     case ISD::SUB:
13320     case ISD::MUL:
13321     case ISD::SHL: {
13322       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13323       if (BinNode->Flags.hasNoSignedWrap())
13324         break;
13325     }
13326     default:
13327       NeedOF = true;
13328       break;
13329     }
13330     break;
13331   }
13332   }
13333   // See if we can use the EFLAGS value from the operand instead of
13334   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13335   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13336   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13337     // Emit a CMP with 0, which is the TEST pattern.
13338     //if (Op.getValueType() == MVT::i1)
13339     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13340     //                     DAG.getConstant(0, MVT::i1));
13341     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13342                        DAG.getConstant(0, dl, Op.getValueType()));
13343   }
13344   unsigned Opcode = 0;
13345   unsigned NumOperands = 0;
13346
13347   // Truncate operations may prevent the merge of the SETCC instruction
13348   // and the arithmetic instruction before it. Attempt to truncate the operands
13349   // of the arithmetic instruction and use a reduced bit-width instruction.
13350   bool NeedTruncation = false;
13351   SDValue ArithOp = Op;
13352   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13353     SDValue Arith = Op->getOperand(0);
13354     // Both the trunc and the arithmetic op need to have one user each.
13355     if (Arith->hasOneUse())
13356       switch (Arith.getOpcode()) {
13357         default: break;
13358         case ISD::ADD:
13359         case ISD::SUB:
13360         case ISD::AND:
13361         case ISD::OR:
13362         case ISD::XOR: {
13363           NeedTruncation = true;
13364           ArithOp = Arith;
13365         }
13366       }
13367   }
13368
13369   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13370   // which may be the result of a CAST.  We use the variable 'Op', which is the
13371   // non-casted variable when we check for possible users.
13372   switch (ArithOp.getOpcode()) {
13373   case ISD::ADD:
13374     // Due to an isel shortcoming, be conservative if this add is likely to be
13375     // selected as part of a load-modify-store instruction. When the root node
13376     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13377     // uses of other nodes in the match, such as the ADD in this case. This
13378     // leads to the ADD being left around and reselected, with the result being
13379     // two adds in the output.  Alas, even if none our users are stores, that
13380     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13381     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13382     // climbing the DAG back to the root, and it doesn't seem to be worth the
13383     // effort.
13384     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13385          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13386       if (UI->getOpcode() != ISD::CopyToReg &&
13387           UI->getOpcode() != ISD::SETCC &&
13388           UI->getOpcode() != ISD::STORE)
13389         goto default_case;
13390
13391     if (ConstantSDNode *C =
13392         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13393       // An add of one will be selected as an INC.
13394       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13395         Opcode = X86ISD::INC;
13396         NumOperands = 1;
13397         break;
13398       }
13399
13400       // An add of negative one (subtract of one) will be selected as a DEC.
13401       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13402         Opcode = X86ISD::DEC;
13403         NumOperands = 1;
13404         break;
13405       }
13406     }
13407
13408     // Otherwise use a regular EFLAGS-setting add.
13409     Opcode = X86ISD::ADD;
13410     NumOperands = 2;
13411     break;
13412   case ISD::SHL:
13413   case ISD::SRL:
13414     // If we have a constant logical shift that's only used in a comparison
13415     // against zero turn it into an equivalent AND. This allows turning it into
13416     // a TEST instruction later.
13417     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13418         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13419       EVT VT = Op.getValueType();
13420       unsigned BitWidth = VT.getSizeInBits();
13421       unsigned ShAmt = Op->getConstantOperandVal(1);
13422       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13423         break;
13424       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13425                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13426                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13427       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13428         break;
13429       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13430                                 DAG.getConstant(Mask, dl, VT));
13431       DAG.ReplaceAllUsesWith(Op, New);
13432       Op = New;
13433     }
13434     break;
13435
13436   case ISD::AND:
13437     // If the primary and result isn't used, don't bother using X86ISD::AND,
13438     // because a TEST instruction will be better.
13439     if (!hasNonFlagsUse(Op))
13440       break;
13441     // FALL THROUGH
13442   case ISD::SUB:
13443   case ISD::OR:
13444   case ISD::XOR:
13445     // Due to the ISEL shortcoming noted above, be conservative if this op is
13446     // likely to be selected as part of a load-modify-store instruction.
13447     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13448            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13449       if (UI->getOpcode() == ISD::STORE)
13450         goto default_case;
13451
13452     // Otherwise use a regular EFLAGS-setting instruction.
13453     switch (ArithOp.getOpcode()) {
13454     default: llvm_unreachable("unexpected operator!");
13455     case ISD::SUB: Opcode = X86ISD::SUB; break;
13456     case ISD::XOR: Opcode = X86ISD::XOR; break;
13457     case ISD::AND: Opcode = X86ISD::AND; break;
13458     case ISD::OR: {
13459       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13460         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13461         if (EFLAGS.getNode())
13462           return EFLAGS;
13463       }
13464       Opcode = X86ISD::OR;
13465       break;
13466     }
13467     }
13468
13469     NumOperands = 2;
13470     break;
13471   case X86ISD::ADD:
13472   case X86ISD::SUB:
13473   case X86ISD::INC:
13474   case X86ISD::DEC:
13475   case X86ISD::OR:
13476   case X86ISD::XOR:
13477   case X86ISD::AND:
13478     return SDValue(Op.getNode(), 1);
13479   default:
13480   default_case:
13481     break;
13482   }
13483
13484   // If we found that truncation is beneficial, perform the truncation and
13485   // update 'Op'.
13486   if (NeedTruncation) {
13487     EVT VT = Op.getValueType();
13488     SDValue WideVal = Op->getOperand(0);
13489     EVT WideVT = WideVal.getValueType();
13490     unsigned ConvertedOp = 0;
13491     // Use a target machine opcode to prevent further DAGCombine
13492     // optimizations that may separate the arithmetic operations
13493     // from the setcc node.
13494     switch (WideVal.getOpcode()) {
13495       default: break;
13496       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13497       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13498       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13499       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13500       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13501     }
13502
13503     if (ConvertedOp) {
13504       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13505       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13506         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13507         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13508         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13509       }
13510     }
13511   }
13512
13513   if (Opcode == 0)
13514     // Emit a CMP with 0, which is the TEST pattern.
13515     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13516                        DAG.getConstant(0, dl, Op.getValueType()));
13517
13518   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13519   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13520
13521   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13522   DAG.ReplaceAllUsesWith(Op, New);
13523   return SDValue(New.getNode(), 1);
13524 }
13525
13526 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13527 /// equivalent.
13528 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13529                                    SDLoc dl, SelectionDAG &DAG) const {
13530   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13531     if (C->getAPIntValue() == 0)
13532       return EmitTest(Op0, X86CC, dl, DAG);
13533
13534      if (Op0.getValueType() == MVT::i1)
13535        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13536   }
13537
13538   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13539        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13540     // Do the comparison at i32 if it's smaller, besides the Atom case.
13541     // This avoids subregister aliasing issues. Keep the smaller reference
13542     // if we're optimizing for size, however, as that'll allow better folding
13543     // of memory operations.
13544     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13545         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13546         !Subtarget->isAtom()) {
13547       unsigned ExtendOp =
13548           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13549       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13550       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13551     }
13552     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13553     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13554     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13555                               Op0, Op1);
13556     return SDValue(Sub.getNode(), 1);
13557   }
13558   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13559 }
13560
13561 /// Convert a comparison if required by the subtarget.
13562 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13563                                                  SelectionDAG &DAG) const {
13564   // If the subtarget does not support the FUCOMI instruction, floating-point
13565   // comparisons have to be converted.
13566   if (Subtarget->hasCMov() ||
13567       Cmp.getOpcode() != X86ISD::CMP ||
13568       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13569       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13570     return Cmp;
13571
13572   // The instruction selector will select an FUCOM instruction instead of
13573   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13574   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13575   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13576   SDLoc dl(Cmp);
13577   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13578   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13579   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13580                             DAG.getConstant(8, dl, MVT::i8));
13581   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13582   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13583 }
13584
13585 /// The minimum architected relative accuracy is 2^-12. We need one
13586 /// Newton-Raphson step to have a good float result (24 bits of precision).
13587 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13588                                             DAGCombinerInfo &DCI,
13589                                             unsigned &RefinementSteps,
13590                                             bool &UseOneConstNR) const {
13591   EVT VT = Op.getValueType();
13592   const char *RecipOp;
13593
13594   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13595   // TODO: Add support for AVX512 (v16f32).
13596   // It is likely not profitable to do this for f64 because a double-precision
13597   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13598   // instructions: convert to single, rsqrtss, convert back to double, refine
13599   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13600   // along with FMA, this could be a throughput win.
13601   if (VT == MVT::f32 && Subtarget->hasSSE1())
13602     RecipOp = "sqrtf";
13603   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13604            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13605     RecipOp = "vec-sqrtf";
13606   else
13607     return SDValue();
13608
13609   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13610   if (!Recips.isEnabled(RecipOp))
13611     return SDValue();
13612
13613   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13614   UseOneConstNR = false;
13615   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13616 }
13617
13618 /// The minimum architected relative accuracy is 2^-12. We need one
13619 /// Newton-Raphson step to have a good float result (24 bits of precision).
13620 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13621                                             DAGCombinerInfo &DCI,
13622                                             unsigned &RefinementSteps) const {
13623   EVT VT = Op.getValueType();
13624   const char *RecipOp;
13625
13626   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13627   // TODO: Add support for AVX512 (v16f32).
13628   // It is likely not profitable to do this for f64 because a double-precision
13629   // reciprocal estimate with refinement on x86 prior to FMA requires
13630   // 15 instructions: convert to single, rcpss, convert back to double, refine
13631   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13632   // along with FMA, this could be a throughput win.
13633   if (VT == MVT::f32 && Subtarget->hasSSE1())
13634     RecipOp = "divf";
13635   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13636            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13637     RecipOp = "vec-divf";
13638   else
13639     return SDValue();
13640
13641   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13642   if (!Recips.isEnabled(RecipOp))
13643     return SDValue();
13644
13645   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13646   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13647 }
13648
13649 /// If we have at least two divisions that use the same divisor, convert to
13650 /// multplication by a reciprocal. This may need to be adjusted for a given
13651 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13652 /// This is because we still need one division to calculate the reciprocal and
13653 /// then we need two multiplies by that reciprocal as replacements for the
13654 /// original divisions.
13655 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13656   return 2;
13657 }
13658
13659 static bool isAllOnes(SDValue V) {
13660   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13661   return C && C->isAllOnesValue();
13662 }
13663
13664 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13665 /// if it's possible.
13666 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13667                                      SDLoc dl, SelectionDAG &DAG) const {
13668   SDValue Op0 = And.getOperand(0);
13669   SDValue Op1 = And.getOperand(1);
13670   if (Op0.getOpcode() == ISD::TRUNCATE)
13671     Op0 = Op0.getOperand(0);
13672   if (Op1.getOpcode() == ISD::TRUNCATE)
13673     Op1 = Op1.getOperand(0);
13674
13675   SDValue LHS, RHS;
13676   if (Op1.getOpcode() == ISD::SHL)
13677     std::swap(Op0, Op1);
13678   if (Op0.getOpcode() == ISD::SHL) {
13679     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13680       if (And00C->getZExtValue() == 1) {
13681         // If we looked past a truncate, check that it's only truncating away
13682         // known zeros.
13683         unsigned BitWidth = Op0.getValueSizeInBits();
13684         unsigned AndBitWidth = And.getValueSizeInBits();
13685         if (BitWidth > AndBitWidth) {
13686           APInt Zeros, Ones;
13687           DAG.computeKnownBits(Op0, Zeros, Ones);
13688           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13689             return SDValue();
13690         }
13691         LHS = Op1;
13692         RHS = Op0.getOperand(1);
13693       }
13694   } else if (Op1.getOpcode() == ISD::Constant) {
13695     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13696     uint64_t AndRHSVal = AndRHS->getZExtValue();
13697     SDValue AndLHS = Op0;
13698
13699     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13700       LHS = AndLHS.getOperand(0);
13701       RHS = AndLHS.getOperand(1);
13702     }
13703
13704     // Use BT if the immediate can't be encoded in a TEST instruction.
13705     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13706       LHS = AndLHS;
13707       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13708     }
13709   }
13710
13711   if (LHS.getNode()) {
13712     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13713     // instruction.  Since the shift amount is in-range-or-undefined, we know
13714     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13715     // the encoding for the i16 version is larger than the i32 version.
13716     // Also promote i16 to i32 for performance / code size reason.
13717     if (LHS.getValueType() == MVT::i8 ||
13718         LHS.getValueType() == MVT::i16)
13719       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13720
13721     // If the operand types disagree, extend the shift amount to match.  Since
13722     // BT ignores high bits (like shifts) we can use anyextend.
13723     if (LHS.getValueType() != RHS.getValueType())
13724       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13725
13726     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13727     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13728     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13729                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13730   }
13731
13732   return SDValue();
13733 }
13734
13735 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13736 /// mask CMPs.
13737 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13738                               SDValue &Op1) {
13739   unsigned SSECC;
13740   bool Swap = false;
13741
13742   // SSE Condition code mapping:
13743   //  0 - EQ
13744   //  1 - LT
13745   //  2 - LE
13746   //  3 - UNORD
13747   //  4 - NEQ
13748   //  5 - NLT
13749   //  6 - NLE
13750   //  7 - ORD
13751   switch (SetCCOpcode) {
13752   default: llvm_unreachable("Unexpected SETCC condition");
13753   case ISD::SETOEQ:
13754   case ISD::SETEQ:  SSECC = 0; break;
13755   case ISD::SETOGT:
13756   case ISD::SETGT:  Swap = true; // Fallthrough
13757   case ISD::SETLT:
13758   case ISD::SETOLT: SSECC = 1; break;
13759   case ISD::SETOGE:
13760   case ISD::SETGE:  Swap = true; // Fallthrough
13761   case ISD::SETLE:
13762   case ISD::SETOLE: SSECC = 2; break;
13763   case ISD::SETUO:  SSECC = 3; break;
13764   case ISD::SETUNE:
13765   case ISD::SETNE:  SSECC = 4; break;
13766   case ISD::SETULE: Swap = true; // Fallthrough
13767   case ISD::SETUGE: SSECC = 5; break;
13768   case ISD::SETULT: Swap = true; // Fallthrough
13769   case ISD::SETUGT: SSECC = 6; break;
13770   case ISD::SETO:   SSECC = 7; break;
13771   case ISD::SETUEQ:
13772   case ISD::SETONE: SSECC = 8; break;
13773   }
13774   if (Swap)
13775     std::swap(Op0, Op1);
13776
13777   return SSECC;
13778 }
13779
13780 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13781 // ones, and then concatenate the result back.
13782 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13783   MVT VT = Op.getSimpleValueType();
13784
13785   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13786          "Unsupported value type for operation");
13787
13788   unsigned NumElems = VT.getVectorNumElements();
13789   SDLoc dl(Op);
13790   SDValue CC = Op.getOperand(2);
13791
13792   // Extract the LHS vectors
13793   SDValue LHS = Op.getOperand(0);
13794   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13795   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13796
13797   // Extract the RHS vectors
13798   SDValue RHS = Op.getOperand(1);
13799   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13800   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13801
13802   // Issue the operation on the smaller types and concatenate the result back
13803   MVT EltVT = VT.getVectorElementType();
13804   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13805   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13806                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13807                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13808 }
13809
13810 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13811   SDValue Op0 = Op.getOperand(0);
13812   SDValue Op1 = Op.getOperand(1);
13813   SDValue CC = Op.getOperand(2);
13814   MVT VT = Op.getSimpleValueType();
13815   SDLoc dl(Op);
13816
13817   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13818          "Unexpected type for boolean compare operation");
13819   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13820   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13821                                DAG.getConstant(-1, dl, VT));
13822   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13823                                DAG.getConstant(-1, dl, VT));
13824   switch (SetCCOpcode) {
13825   default: llvm_unreachable("Unexpected SETCC condition");
13826   case ISD::SETEQ:
13827     // (x == y) -> ~(x ^ y)
13828     return DAG.getNode(ISD::XOR, dl, VT,
13829                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13830                        DAG.getConstant(-1, dl, VT));
13831   case ISD::SETNE:
13832     // (x != y) -> (x ^ y)
13833     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13834   case ISD::SETUGT:
13835   case ISD::SETGT:
13836     // (x > y) -> (x & ~y)
13837     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13838   case ISD::SETULT:
13839   case ISD::SETLT:
13840     // (x < y) -> (~x & y)
13841     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13842   case ISD::SETULE:
13843   case ISD::SETLE:
13844     // (x <= y) -> (~x | y)
13845     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13846   case ISD::SETUGE:
13847   case ISD::SETGE:
13848     // (x >=y) -> (x | ~y)
13849     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13850   }
13851 }
13852
13853 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13854                                      const X86Subtarget *Subtarget) {
13855   SDValue Op0 = Op.getOperand(0);
13856   SDValue Op1 = Op.getOperand(1);
13857   SDValue CC = Op.getOperand(2);
13858   MVT VT = Op.getSimpleValueType();
13859   SDLoc dl(Op);
13860
13861   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13862          Op.getValueType().getScalarType() == MVT::i1 &&
13863          "Cannot set masked compare for this operation");
13864
13865   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13866   unsigned  Opc = 0;
13867   bool Unsigned = false;
13868   bool Swap = false;
13869   unsigned SSECC;
13870   switch (SetCCOpcode) {
13871   default: llvm_unreachable("Unexpected SETCC condition");
13872   case ISD::SETNE:  SSECC = 4; break;
13873   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13874   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13875   case ISD::SETLT:  Swap = true; //fall-through
13876   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13877   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13878   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13879   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13880   case ISD::SETULE: Unsigned = true; //fall-through
13881   case ISD::SETLE:  SSECC = 2; break;
13882   }
13883
13884   if (Swap)
13885     std::swap(Op0, Op1);
13886   if (Opc)
13887     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13888   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13889   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13890                      DAG.getConstant(SSECC, dl, MVT::i8));
13891 }
13892
13893 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13894 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13895 /// return an empty value.
13896 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13897 {
13898   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13899   if (!BV)
13900     return SDValue();
13901
13902   MVT VT = Op1.getSimpleValueType();
13903   MVT EVT = VT.getVectorElementType();
13904   unsigned n = VT.getVectorNumElements();
13905   SmallVector<SDValue, 8> ULTOp1;
13906
13907   for (unsigned i = 0; i < n; ++i) {
13908     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13909     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13910       return SDValue();
13911
13912     // Avoid underflow.
13913     APInt Val = Elt->getAPIntValue();
13914     if (Val == 0)
13915       return SDValue();
13916
13917     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13918   }
13919
13920   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13921 }
13922
13923 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13924                            SelectionDAG &DAG) {
13925   SDValue Op0 = Op.getOperand(0);
13926   SDValue Op1 = Op.getOperand(1);
13927   SDValue CC = Op.getOperand(2);
13928   MVT VT = Op.getSimpleValueType();
13929   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13930   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13931   SDLoc dl(Op);
13932
13933   if (isFP) {
13934 #ifndef NDEBUG
13935     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13936     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13937 #endif
13938
13939     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13940     unsigned Opc = X86ISD::CMPP;
13941     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13942       assert(VT.getVectorNumElements() <= 16);
13943       Opc = X86ISD::CMPM;
13944     }
13945     // In the two special cases we can't handle, emit two comparisons.
13946     if (SSECC == 8) {
13947       unsigned CC0, CC1;
13948       unsigned CombineOpc;
13949       if (SetCCOpcode == ISD::SETUEQ) {
13950         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13951       } else {
13952         assert(SetCCOpcode == ISD::SETONE);
13953         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13954       }
13955
13956       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13957                                  DAG.getConstant(CC0, dl, MVT::i8));
13958       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13959                                  DAG.getConstant(CC1, dl, MVT::i8));
13960       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13961     }
13962     // Handle all other FP comparisons here.
13963     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13964                        DAG.getConstant(SSECC, dl, MVT::i8));
13965   }
13966
13967   // Break 256-bit integer vector compare into smaller ones.
13968   if (VT.is256BitVector() && !Subtarget->hasInt256())
13969     return Lower256IntVSETCC(Op, DAG);
13970
13971   EVT OpVT = Op1.getValueType();
13972   if (OpVT.getVectorElementType() == MVT::i1)
13973     return LowerBoolVSETCC_AVX512(Op, DAG);
13974
13975   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13976   if (Subtarget->hasAVX512()) {
13977     if (Op1.getValueType().is512BitVector() ||
13978         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13979         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13980       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13981
13982     // In AVX-512 architecture setcc returns mask with i1 elements,
13983     // But there is no compare instruction for i8 and i16 elements in KNL.
13984     // We are not talking about 512-bit operands in this case, these
13985     // types are illegal.
13986     if (MaskResult &&
13987         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13988          OpVT.getVectorElementType().getSizeInBits() >= 8))
13989       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13990                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13991   }
13992
13993   // We are handling one of the integer comparisons here.  Since SSE only has
13994   // GT and EQ comparisons for integer, swapping operands and multiple
13995   // operations may be required for some comparisons.
13996   unsigned Opc;
13997   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13998   bool Subus = false;
13999
14000   switch (SetCCOpcode) {
14001   default: llvm_unreachable("Unexpected SETCC condition");
14002   case ISD::SETNE:  Invert = true;
14003   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14004   case ISD::SETLT:  Swap = true;
14005   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14006   case ISD::SETGE:  Swap = true;
14007   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14008                     Invert = true; break;
14009   case ISD::SETULT: Swap = true;
14010   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14011                     FlipSigns = true; break;
14012   case ISD::SETUGE: Swap = true;
14013   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14014                     FlipSigns = true; Invert = true; break;
14015   }
14016
14017   // Special case: Use min/max operations for SETULE/SETUGE
14018   MVT VET = VT.getVectorElementType();
14019   bool hasMinMax =
14020        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14021     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14022
14023   if (hasMinMax) {
14024     switch (SetCCOpcode) {
14025     default: break;
14026     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14027     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14028     }
14029
14030     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14031   }
14032
14033   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14034   if (!MinMax && hasSubus) {
14035     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14036     // Op0 u<= Op1:
14037     //   t = psubus Op0, Op1
14038     //   pcmpeq t, <0..0>
14039     switch (SetCCOpcode) {
14040     default: break;
14041     case ISD::SETULT: {
14042       // If the comparison is against a constant we can turn this into a
14043       // setule.  With psubus, setule does not require a swap.  This is
14044       // beneficial because the constant in the register is no longer
14045       // destructed as the destination so it can be hoisted out of a loop.
14046       // Only do this pre-AVX since vpcmp* is no longer destructive.
14047       if (Subtarget->hasAVX())
14048         break;
14049       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14050       if (ULEOp1.getNode()) {
14051         Op1 = ULEOp1;
14052         Subus = true; Invert = false; Swap = false;
14053       }
14054       break;
14055     }
14056     // Psubus is better than flip-sign because it requires no inversion.
14057     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14058     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14059     }
14060
14061     if (Subus) {
14062       Opc = X86ISD::SUBUS;
14063       FlipSigns = false;
14064     }
14065   }
14066
14067   if (Swap)
14068     std::swap(Op0, Op1);
14069
14070   // Check that the operation in question is available (most are plain SSE2,
14071   // but PCMPGTQ and PCMPEQQ have different requirements).
14072   if (VT == MVT::v2i64) {
14073     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14074       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14075
14076       // First cast everything to the right type.
14077       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14078       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14079
14080       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14081       // bits of the inputs before performing those operations. The lower
14082       // compare is always unsigned.
14083       SDValue SB;
14084       if (FlipSigns) {
14085         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14086       } else {
14087         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14088         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14089         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14090                          Sign, Zero, Sign, Zero);
14091       }
14092       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14093       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14094
14095       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14096       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14097       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14098
14099       // Create masks for only the low parts/high parts of the 64 bit integers.
14100       static const int MaskHi[] = { 1, 1, 3, 3 };
14101       static const int MaskLo[] = { 0, 0, 2, 2 };
14102       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14103       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14104       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14105
14106       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14107       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14108
14109       if (Invert)
14110         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14111
14112       return DAG.getBitcast(VT, Result);
14113     }
14114
14115     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14116       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14117       // pcmpeqd + pshufd + pand.
14118       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14119
14120       // First cast everything to the right type.
14121       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14122       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14123
14124       // Do the compare.
14125       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14126
14127       // Make sure the lower and upper halves are both all-ones.
14128       static const int Mask[] = { 1, 0, 3, 2 };
14129       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14130       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14131
14132       if (Invert)
14133         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14134
14135       return DAG.getBitcast(VT, Result);
14136     }
14137   }
14138
14139   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14140   // bits of the inputs before performing those operations.
14141   if (FlipSigns) {
14142     EVT EltVT = VT.getVectorElementType();
14143     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14144                                  VT);
14145     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14146     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14147   }
14148
14149   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14150
14151   // If the logical-not of the result is required, perform that now.
14152   if (Invert)
14153     Result = DAG.getNOT(dl, Result, VT);
14154
14155   if (MinMax)
14156     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14157
14158   if (Subus)
14159     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14160                          getZeroVector(VT, Subtarget, DAG, dl));
14161
14162   return Result;
14163 }
14164
14165 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14166
14167   MVT VT = Op.getSimpleValueType();
14168
14169   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14170
14171   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14172          && "SetCC type must be 8-bit or 1-bit integer");
14173   SDValue Op0 = Op.getOperand(0);
14174   SDValue Op1 = Op.getOperand(1);
14175   SDLoc dl(Op);
14176   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14177
14178   // Optimize to BT if possible.
14179   // Lower (X & (1 << N)) == 0 to BT(X, N).
14180   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14181   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14182   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14183       Op1.getOpcode() == ISD::Constant &&
14184       cast<ConstantSDNode>(Op1)->isNullValue() &&
14185       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14186     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14187     if (NewSetCC.getNode()) {
14188       if (VT == MVT::i1)
14189         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14190       return NewSetCC;
14191     }
14192   }
14193
14194   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14195   // these.
14196   if (Op1.getOpcode() == ISD::Constant &&
14197       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14198        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14199       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14200
14201     // If the input is a setcc, then reuse the input setcc or use a new one with
14202     // the inverted condition.
14203     if (Op0.getOpcode() == X86ISD::SETCC) {
14204       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14205       bool Invert = (CC == ISD::SETNE) ^
14206         cast<ConstantSDNode>(Op1)->isNullValue();
14207       if (!Invert)
14208         return Op0;
14209
14210       CCode = X86::GetOppositeBranchCondition(CCode);
14211       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14212                                   DAG.getConstant(CCode, dl, MVT::i8),
14213                                   Op0.getOperand(1));
14214       if (VT == MVT::i1)
14215         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14216       return SetCC;
14217     }
14218   }
14219   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14220       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14221       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14222
14223     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14224     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14225   }
14226
14227   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14228   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14229   if (X86CC == X86::COND_INVALID)
14230     return SDValue();
14231
14232   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14233   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14234   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14235                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14236   if (VT == MVT::i1)
14237     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14238   return SetCC;
14239 }
14240
14241 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14242 static bool isX86LogicalCmp(SDValue Op) {
14243   unsigned Opc = Op.getNode()->getOpcode();
14244   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14245       Opc == X86ISD::SAHF)
14246     return true;
14247   if (Op.getResNo() == 1 &&
14248       (Opc == X86ISD::ADD ||
14249        Opc == X86ISD::SUB ||
14250        Opc == X86ISD::ADC ||
14251        Opc == X86ISD::SBB ||
14252        Opc == X86ISD::SMUL ||
14253        Opc == X86ISD::UMUL ||
14254        Opc == X86ISD::INC ||
14255        Opc == X86ISD::DEC ||
14256        Opc == X86ISD::OR ||
14257        Opc == X86ISD::XOR ||
14258        Opc == X86ISD::AND))
14259     return true;
14260
14261   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14262     return true;
14263
14264   return false;
14265 }
14266
14267 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14268   if (V.getOpcode() != ISD::TRUNCATE)
14269     return false;
14270
14271   SDValue VOp0 = V.getOperand(0);
14272   unsigned InBits = VOp0.getValueSizeInBits();
14273   unsigned Bits = V.getValueSizeInBits();
14274   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14275 }
14276
14277 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14278   bool addTest = true;
14279   SDValue Cond  = Op.getOperand(0);
14280   SDValue Op1 = Op.getOperand(1);
14281   SDValue Op2 = Op.getOperand(2);
14282   SDLoc DL(Op);
14283   EVT VT = Op1.getValueType();
14284   SDValue CC;
14285
14286   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14287   // are available or VBLENDV if AVX is available.
14288   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14289   if (Cond.getOpcode() == ISD::SETCC &&
14290       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14291        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14292       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14293     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14294     int SSECC = translateX86FSETCC(
14295         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14296
14297     if (SSECC != 8) {
14298       if (Subtarget->hasAVX512()) {
14299         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14300                                   DAG.getConstant(SSECC, DL, MVT::i8));
14301         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14302       }
14303
14304       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14305                                 DAG.getConstant(SSECC, DL, MVT::i8));
14306
14307       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14308       // of 3 logic instructions for size savings and potentially speed.
14309       // Unfortunately, there is no scalar form of VBLENDV.
14310
14311       // If either operand is a constant, don't try this. We can expect to
14312       // optimize away at least one of the logic instructions later in that
14313       // case, so that sequence would be faster than a variable blend.
14314
14315       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14316       // uses XMM0 as the selection register. That may need just as many
14317       // instructions as the AND/ANDN/OR sequence due to register moves, so
14318       // don't bother.
14319
14320       if (Subtarget->hasAVX() &&
14321           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14322
14323         // Convert to vectors, do a VSELECT, and convert back to scalar.
14324         // All of the conversions should be optimized away.
14325
14326         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14327         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14328         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14329         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14330
14331         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14332         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14333
14334         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14335
14336         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14337                            VSel, DAG.getIntPtrConstant(0, DL));
14338       }
14339       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14340       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14341       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14342     }
14343   }
14344
14345   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14346     SDValue Op1Scalar;
14347     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14348       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14349     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14350       Op1Scalar = Op1.getOperand(0);
14351     SDValue Op2Scalar;
14352     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14353       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14354     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14355       Op2Scalar = Op2.getOperand(0);
14356     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14357       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14358                                       Op1Scalar.getValueType(),
14359                                       Cond, Op1Scalar, Op2Scalar);
14360       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14361         return DAG.getBitcast(VT, newSelect);
14362       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14363       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14364                          DAG.getIntPtrConstant(0, DL));
14365     }
14366   }
14367
14368   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14369     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14370     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14371                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14372     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14373                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14374     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14375                                     Cond, Op1, Op2);
14376     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14377   }
14378
14379   if (Cond.getOpcode() == ISD::SETCC) {
14380     SDValue NewCond = LowerSETCC(Cond, DAG);
14381     if (NewCond.getNode())
14382       Cond = NewCond;
14383   }
14384
14385   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14386   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14387   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14388   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14389   if (Cond.getOpcode() == X86ISD::SETCC &&
14390       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14391       isZero(Cond.getOperand(1).getOperand(1))) {
14392     SDValue Cmp = Cond.getOperand(1);
14393
14394     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14395
14396     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14397         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14398       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14399
14400       SDValue CmpOp0 = Cmp.getOperand(0);
14401       // Apply further optimizations for special cases
14402       // (select (x != 0), -1, 0) -> neg & sbb
14403       // (select (x == 0), 0, -1) -> neg & sbb
14404       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14405         if (YC->isNullValue() &&
14406             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14407           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14408           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14409                                     DAG.getConstant(0, DL,
14410                                                     CmpOp0.getValueType()),
14411                                     CmpOp0);
14412           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14413                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14414                                     SDValue(Neg.getNode(), 1));
14415           return Res;
14416         }
14417
14418       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14419                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14420       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14421
14422       SDValue Res =   // Res = 0 or -1.
14423         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14424                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14425
14426       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14427         Res = DAG.getNOT(DL, Res, Res.getValueType());
14428
14429       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14430       if (!N2C || !N2C->isNullValue())
14431         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14432       return Res;
14433     }
14434   }
14435
14436   // Look past (and (setcc_carry (cmp ...)), 1).
14437   if (Cond.getOpcode() == ISD::AND &&
14438       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14439     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14440     if (C && C->getAPIntValue() == 1)
14441       Cond = Cond.getOperand(0);
14442   }
14443
14444   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14445   // setting operand in place of the X86ISD::SETCC.
14446   unsigned CondOpcode = Cond.getOpcode();
14447   if (CondOpcode == X86ISD::SETCC ||
14448       CondOpcode == X86ISD::SETCC_CARRY) {
14449     CC = Cond.getOperand(0);
14450
14451     SDValue Cmp = Cond.getOperand(1);
14452     unsigned Opc = Cmp.getOpcode();
14453     MVT VT = Op.getSimpleValueType();
14454
14455     bool IllegalFPCMov = false;
14456     if (VT.isFloatingPoint() && !VT.isVector() &&
14457         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14458       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14459
14460     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14461         Opc == X86ISD::BT) { // FIXME
14462       Cond = Cmp;
14463       addTest = false;
14464     }
14465   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14466              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14467              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14468               Cond.getOperand(0).getValueType() != MVT::i8)) {
14469     SDValue LHS = Cond.getOperand(0);
14470     SDValue RHS = Cond.getOperand(1);
14471     unsigned X86Opcode;
14472     unsigned X86Cond;
14473     SDVTList VTs;
14474     switch (CondOpcode) {
14475     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14476     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14477     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14478     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14479     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14480     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14481     default: llvm_unreachable("unexpected overflowing operator");
14482     }
14483     if (CondOpcode == ISD::UMULO)
14484       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14485                           MVT::i32);
14486     else
14487       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14488
14489     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14490
14491     if (CondOpcode == ISD::UMULO)
14492       Cond = X86Op.getValue(2);
14493     else
14494       Cond = X86Op.getValue(1);
14495
14496     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14497     addTest = false;
14498   }
14499
14500   if (addTest) {
14501     // Look past the truncate if the high bits are known zero.
14502     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14503       Cond = Cond.getOperand(0);
14504
14505     // We know the result of AND is compared against zero. Try to match
14506     // it to BT.
14507     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14508       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14509       if (NewSetCC.getNode()) {
14510         CC = NewSetCC.getOperand(0);
14511         Cond = NewSetCC.getOperand(1);
14512         addTest = false;
14513       }
14514     }
14515   }
14516
14517   if (addTest) {
14518     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14519     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14520   }
14521
14522   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14523   // a <  b ?  0 : -1 -> RES = setcc_carry
14524   // a >= b ? -1 :  0 -> RES = setcc_carry
14525   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14526   if (Cond.getOpcode() == X86ISD::SUB) {
14527     Cond = ConvertCmpIfNecessary(Cond, DAG);
14528     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14529
14530     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14531         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14532       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14533                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14534                                 Cond);
14535       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14536         return DAG.getNOT(DL, Res, Res.getValueType());
14537       return Res;
14538     }
14539   }
14540
14541   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14542   // widen the cmov and push the truncate through. This avoids introducing a new
14543   // branch during isel and doesn't add any extensions.
14544   if (Op.getValueType() == MVT::i8 &&
14545       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14546     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14547     if (T1.getValueType() == T2.getValueType() &&
14548         // Blacklist CopyFromReg to avoid partial register stalls.
14549         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14550       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14551       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14552       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14553     }
14554   }
14555
14556   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14557   // condition is true.
14558   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14559   SDValue Ops[] = { Op2, Op1, CC, Cond };
14560   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14561 }
14562
14563 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14564                                        const X86Subtarget *Subtarget,
14565                                        SelectionDAG &DAG) {
14566   MVT VT = Op->getSimpleValueType(0);
14567   SDValue In = Op->getOperand(0);
14568   MVT InVT = In.getSimpleValueType();
14569   MVT VTElt = VT.getVectorElementType();
14570   MVT InVTElt = InVT.getVectorElementType();
14571   SDLoc dl(Op);
14572
14573   // SKX processor
14574   if ((InVTElt == MVT::i1) &&
14575       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14576         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14577
14578        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14579         VTElt.getSizeInBits() <= 16)) ||
14580
14581        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14582         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14583
14584        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14585         VTElt.getSizeInBits() >= 32))))
14586     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14587
14588   unsigned int NumElts = VT.getVectorNumElements();
14589
14590   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14591     return SDValue();
14592
14593   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14594     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14595       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14596     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14597   }
14598
14599   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14600   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14601   SDValue NegOne =
14602    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14603                    ExtVT);
14604   SDValue Zero =
14605    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14606
14607   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14608   if (VT.is512BitVector())
14609     return V;
14610   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14611 }
14612
14613 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14614                                              const X86Subtarget *Subtarget,
14615                                              SelectionDAG &DAG) {
14616   SDValue In = Op->getOperand(0);
14617   MVT VT = Op->getSimpleValueType(0);
14618   MVT InVT = In.getSimpleValueType();
14619   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14620
14621   MVT InSVT = InVT.getScalarType();
14622   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14623
14624   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14625     return SDValue();
14626   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14627     return SDValue();
14628
14629   SDLoc dl(Op);
14630
14631   // SSE41 targets can use the pmovsx* instructions directly.
14632   if (Subtarget->hasSSE41())
14633     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14634
14635   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14636   SDValue Curr = In;
14637   MVT CurrVT = InVT;
14638
14639   // As SRAI is only available on i16/i32 types, we expand only up to i32
14640   // and handle i64 separately.
14641   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14642     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14643     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14644     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14645     Curr = DAG.getBitcast(CurrVT, Curr);
14646   }
14647
14648   SDValue SignExt = Curr;
14649   if (CurrVT != InVT) {
14650     unsigned SignExtShift =
14651         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14652     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14653                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14654   }
14655
14656   if (CurrVT == VT)
14657     return SignExt;
14658
14659   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14660     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14661                                DAG.getConstant(31, dl, MVT::i8));
14662     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14663     return DAG.getBitcast(VT, Ext);
14664   }
14665
14666   return SDValue();
14667 }
14668
14669 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14670                                 SelectionDAG &DAG) {
14671   MVT VT = Op->getSimpleValueType(0);
14672   SDValue In = Op->getOperand(0);
14673   MVT InVT = In.getSimpleValueType();
14674   SDLoc dl(Op);
14675
14676   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14677     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14678
14679   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14680       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14681       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14682     return SDValue();
14683
14684   if (Subtarget->hasInt256())
14685     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14686
14687   // Optimize vectors in AVX mode
14688   // Sign extend  v8i16 to v8i32 and
14689   //              v4i32 to v4i64
14690   //
14691   // Divide input vector into two parts
14692   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14693   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14694   // concat the vectors to original VT
14695
14696   unsigned NumElems = InVT.getVectorNumElements();
14697   SDValue Undef = DAG.getUNDEF(InVT);
14698
14699   SmallVector<int,8> ShufMask1(NumElems, -1);
14700   for (unsigned i = 0; i != NumElems/2; ++i)
14701     ShufMask1[i] = i;
14702
14703   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14704
14705   SmallVector<int,8> ShufMask2(NumElems, -1);
14706   for (unsigned i = 0; i != NumElems/2; ++i)
14707     ShufMask2[i] = i + NumElems/2;
14708
14709   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14710
14711   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14712                                 VT.getVectorNumElements()/2);
14713
14714   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14715   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14716
14717   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14718 }
14719
14720 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14721 // may emit an illegal shuffle but the expansion is still better than scalar
14722 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14723 // we'll emit a shuffle and a arithmetic shift.
14724 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14725 // TODO: It is possible to support ZExt by zeroing the undef values during
14726 // the shuffle phase or after the shuffle.
14727 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14728                                  SelectionDAG &DAG) {
14729   MVT RegVT = Op.getSimpleValueType();
14730   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14731   assert(RegVT.isInteger() &&
14732          "We only custom lower integer vector sext loads.");
14733
14734   // Nothing useful we can do without SSE2 shuffles.
14735   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14736
14737   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14738   SDLoc dl(Ld);
14739   EVT MemVT = Ld->getMemoryVT();
14740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14741   unsigned RegSz = RegVT.getSizeInBits();
14742
14743   ISD::LoadExtType Ext = Ld->getExtensionType();
14744
14745   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14746          && "Only anyext and sext are currently implemented.");
14747   assert(MemVT != RegVT && "Cannot extend to the same type");
14748   assert(MemVT.isVector() && "Must load a vector from memory");
14749
14750   unsigned NumElems = RegVT.getVectorNumElements();
14751   unsigned MemSz = MemVT.getSizeInBits();
14752   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14753
14754   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14755     // The only way in which we have a legal 256-bit vector result but not the
14756     // integer 256-bit operations needed to directly lower a sextload is if we
14757     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14758     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14759     // correctly legalized. We do this late to allow the canonical form of
14760     // sextload to persist throughout the rest of the DAG combiner -- it wants
14761     // to fold together any extensions it can, and so will fuse a sign_extend
14762     // of an sextload into a sextload targeting a wider value.
14763     SDValue Load;
14764     if (MemSz == 128) {
14765       // Just switch this to a normal load.
14766       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14767                                        "it must be a legal 128-bit vector "
14768                                        "type!");
14769       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14770                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14771                   Ld->isInvariant(), Ld->getAlignment());
14772     } else {
14773       assert(MemSz < 128 &&
14774              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14775       // Do an sext load to a 128-bit vector type. We want to use the same
14776       // number of elements, but elements half as wide. This will end up being
14777       // recursively lowered by this routine, but will succeed as we definitely
14778       // have all the necessary features if we're using AVX1.
14779       EVT HalfEltVT =
14780           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14781       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14782       Load =
14783           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14784                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14785                          Ld->isNonTemporal(), Ld->isInvariant(),
14786                          Ld->getAlignment());
14787     }
14788
14789     // Replace chain users with the new chain.
14790     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14791     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14792
14793     // Finally, do a normal sign-extend to the desired register.
14794     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14795   }
14796
14797   // All sizes must be a power of two.
14798   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14799          "Non-power-of-two elements are not custom lowered!");
14800
14801   // Attempt to load the original value using scalar loads.
14802   // Find the largest scalar type that divides the total loaded size.
14803   MVT SclrLoadTy = MVT::i8;
14804   for (MVT Tp : MVT::integer_valuetypes()) {
14805     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14806       SclrLoadTy = Tp;
14807     }
14808   }
14809
14810   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14811   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14812       (64 <= MemSz))
14813     SclrLoadTy = MVT::f64;
14814
14815   // Calculate the number of scalar loads that we need to perform
14816   // in order to load our vector from memory.
14817   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14818
14819   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14820          "Can only lower sext loads with a single scalar load!");
14821
14822   unsigned loadRegZize = RegSz;
14823   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14824     loadRegZize = 128;
14825
14826   // Represent our vector as a sequence of elements which are the
14827   // largest scalar that we can load.
14828   EVT LoadUnitVecVT = EVT::getVectorVT(
14829       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14830
14831   // Represent the data using the same element type that is stored in
14832   // memory. In practice, we ''widen'' MemVT.
14833   EVT WideVecVT =
14834       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14835                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14836
14837   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14838          "Invalid vector type");
14839
14840   // We can't shuffle using an illegal type.
14841   assert(TLI.isTypeLegal(WideVecVT) &&
14842          "We only lower types that form legal widened vector types");
14843
14844   SmallVector<SDValue, 8> Chains;
14845   SDValue Ptr = Ld->getBasePtr();
14846   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14847                                       TLI.getPointerTy(DAG.getDataLayout()));
14848   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14849
14850   for (unsigned i = 0; i < NumLoads; ++i) {
14851     // Perform a single load.
14852     SDValue ScalarLoad =
14853         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14854                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14855                     Ld->getAlignment());
14856     Chains.push_back(ScalarLoad.getValue(1));
14857     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14858     // another round of DAGCombining.
14859     if (i == 0)
14860       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14861     else
14862       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14863                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14864
14865     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14866   }
14867
14868   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14869
14870   // Bitcast the loaded value to a vector of the original element type, in
14871   // the size of the target vector type.
14872   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14873   unsigned SizeRatio = RegSz / MemSz;
14874
14875   if (Ext == ISD::SEXTLOAD) {
14876     // If we have SSE4.1, we can directly emit a VSEXT node.
14877     if (Subtarget->hasSSE41()) {
14878       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14879       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14880       return Sext;
14881     }
14882
14883     // Otherwise we'll shuffle the small elements in the high bits of the
14884     // larger type and perform an arithmetic shift. If the shift is not legal
14885     // it's better to scalarize.
14886     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14887            "We can't implement a sext load without an arithmetic right shift!");
14888
14889     // Redistribute the loaded elements into the different locations.
14890     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14891     for (unsigned i = 0; i != NumElems; ++i)
14892       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14893
14894     SDValue Shuff = DAG.getVectorShuffle(
14895         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14896
14897     Shuff = DAG.getBitcast(RegVT, Shuff);
14898
14899     // Build the arithmetic shift.
14900     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14901                    MemVT.getVectorElementType().getSizeInBits();
14902     Shuff =
14903         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14904                     DAG.getConstant(Amt, dl, RegVT));
14905
14906     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14907     return Shuff;
14908   }
14909
14910   // Redistribute the loaded elements into the different locations.
14911   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14912   for (unsigned i = 0; i != NumElems; ++i)
14913     ShuffleVec[i * SizeRatio] = i;
14914
14915   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14916                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14917
14918   // Bitcast to the requested type.
14919   Shuff = DAG.getBitcast(RegVT, Shuff);
14920   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14921   return Shuff;
14922 }
14923
14924 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14925 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14926 // from the AND / OR.
14927 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14928   Opc = Op.getOpcode();
14929   if (Opc != ISD::OR && Opc != ISD::AND)
14930     return false;
14931   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14932           Op.getOperand(0).hasOneUse() &&
14933           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14934           Op.getOperand(1).hasOneUse());
14935 }
14936
14937 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14938 // 1 and that the SETCC node has a single use.
14939 static bool isXor1OfSetCC(SDValue Op) {
14940   if (Op.getOpcode() != ISD::XOR)
14941     return false;
14942   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14943   if (N1C && N1C->getAPIntValue() == 1) {
14944     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14945       Op.getOperand(0).hasOneUse();
14946   }
14947   return false;
14948 }
14949
14950 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14951   bool addTest = true;
14952   SDValue Chain = Op.getOperand(0);
14953   SDValue Cond  = Op.getOperand(1);
14954   SDValue Dest  = Op.getOperand(2);
14955   SDLoc dl(Op);
14956   SDValue CC;
14957   bool Inverted = false;
14958
14959   if (Cond.getOpcode() == ISD::SETCC) {
14960     // Check for setcc([su]{add,sub,mul}o == 0).
14961     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14962         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14963         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14964         Cond.getOperand(0).getResNo() == 1 &&
14965         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14966          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14967          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14968          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14969          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14970          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14971       Inverted = true;
14972       Cond = Cond.getOperand(0);
14973     } else {
14974       SDValue NewCond = LowerSETCC(Cond, DAG);
14975       if (NewCond.getNode())
14976         Cond = NewCond;
14977     }
14978   }
14979 #if 0
14980   // FIXME: LowerXALUO doesn't handle these!!
14981   else if (Cond.getOpcode() == X86ISD::ADD  ||
14982            Cond.getOpcode() == X86ISD::SUB  ||
14983            Cond.getOpcode() == X86ISD::SMUL ||
14984            Cond.getOpcode() == X86ISD::UMUL)
14985     Cond = LowerXALUO(Cond, DAG);
14986 #endif
14987
14988   // Look pass (and (setcc_carry (cmp ...)), 1).
14989   if (Cond.getOpcode() == ISD::AND &&
14990       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14991     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14992     if (C && C->getAPIntValue() == 1)
14993       Cond = Cond.getOperand(0);
14994   }
14995
14996   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14997   // setting operand in place of the X86ISD::SETCC.
14998   unsigned CondOpcode = Cond.getOpcode();
14999   if (CondOpcode == X86ISD::SETCC ||
15000       CondOpcode == X86ISD::SETCC_CARRY) {
15001     CC = Cond.getOperand(0);
15002
15003     SDValue Cmp = Cond.getOperand(1);
15004     unsigned Opc = Cmp.getOpcode();
15005     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15006     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15007       Cond = Cmp;
15008       addTest = false;
15009     } else {
15010       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15011       default: break;
15012       case X86::COND_O:
15013       case X86::COND_B:
15014         // These can only come from an arithmetic instruction with overflow,
15015         // e.g. SADDO, UADDO.
15016         Cond = Cond.getNode()->getOperand(1);
15017         addTest = false;
15018         break;
15019       }
15020     }
15021   }
15022   CondOpcode = Cond.getOpcode();
15023   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15024       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15025       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15026        Cond.getOperand(0).getValueType() != MVT::i8)) {
15027     SDValue LHS = Cond.getOperand(0);
15028     SDValue RHS = Cond.getOperand(1);
15029     unsigned X86Opcode;
15030     unsigned X86Cond;
15031     SDVTList VTs;
15032     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15033     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15034     // X86ISD::INC).
15035     switch (CondOpcode) {
15036     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15037     case ISD::SADDO:
15038       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15039         if (C->isOne()) {
15040           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15041           break;
15042         }
15043       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15044     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15045     case ISD::SSUBO:
15046       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15047         if (C->isOne()) {
15048           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15049           break;
15050         }
15051       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15052     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15053     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15054     default: llvm_unreachable("unexpected overflowing operator");
15055     }
15056     if (Inverted)
15057       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15058     if (CondOpcode == ISD::UMULO)
15059       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15060                           MVT::i32);
15061     else
15062       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15063
15064     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15065
15066     if (CondOpcode == ISD::UMULO)
15067       Cond = X86Op.getValue(2);
15068     else
15069       Cond = X86Op.getValue(1);
15070
15071     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15072     addTest = false;
15073   } else {
15074     unsigned CondOpc;
15075     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15076       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15077       if (CondOpc == ISD::OR) {
15078         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15079         // two branches instead of an explicit OR instruction with a
15080         // separate test.
15081         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15082             isX86LogicalCmp(Cmp)) {
15083           CC = Cond.getOperand(0).getOperand(0);
15084           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15085                               Chain, Dest, CC, Cmp);
15086           CC = Cond.getOperand(1).getOperand(0);
15087           Cond = Cmp;
15088           addTest = false;
15089         }
15090       } else { // ISD::AND
15091         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15092         // two branches instead of an explicit AND instruction with a
15093         // separate test. However, we only do this if this block doesn't
15094         // have a fall-through edge, because this requires an explicit
15095         // jmp when the condition is false.
15096         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15097             isX86LogicalCmp(Cmp) &&
15098             Op.getNode()->hasOneUse()) {
15099           X86::CondCode CCode =
15100             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15101           CCode = X86::GetOppositeBranchCondition(CCode);
15102           CC = DAG.getConstant(CCode, dl, MVT::i8);
15103           SDNode *User = *Op.getNode()->use_begin();
15104           // Look for an unconditional branch following this conditional branch.
15105           // We need this because we need to reverse the successors in order
15106           // to implement FCMP_OEQ.
15107           if (User->getOpcode() == ISD::BR) {
15108             SDValue FalseBB = User->getOperand(1);
15109             SDNode *NewBR =
15110               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15111             assert(NewBR == User);
15112             (void)NewBR;
15113             Dest = FalseBB;
15114
15115             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15116                                 Chain, Dest, CC, Cmp);
15117             X86::CondCode CCode =
15118               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15119             CCode = X86::GetOppositeBranchCondition(CCode);
15120             CC = DAG.getConstant(CCode, dl, MVT::i8);
15121             Cond = Cmp;
15122             addTest = false;
15123           }
15124         }
15125       }
15126     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15127       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15128       // It should be transformed during dag combiner except when the condition
15129       // is set by a arithmetics with overflow node.
15130       X86::CondCode CCode =
15131         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15132       CCode = X86::GetOppositeBranchCondition(CCode);
15133       CC = DAG.getConstant(CCode, dl, MVT::i8);
15134       Cond = Cond.getOperand(0).getOperand(1);
15135       addTest = false;
15136     } else if (Cond.getOpcode() == ISD::SETCC &&
15137                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15138       // For FCMP_OEQ, we can emit
15139       // two branches instead of an explicit AND instruction with a
15140       // separate test. However, we only do this if this block doesn't
15141       // have a fall-through edge, because this requires an explicit
15142       // jmp when the condition is false.
15143       if (Op.getNode()->hasOneUse()) {
15144         SDNode *User = *Op.getNode()->use_begin();
15145         // Look for an unconditional branch following this conditional branch.
15146         // We need this because we need to reverse the successors in order
15147         // to implement FCMP_OEQ.
15148         if (User->getOpcode() == ISD::BR) {
15149           SDValue FalseBB = User->getOperand(1);
15150           SDNode *NewBR =
15151             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15152           assert(NewBR == User);
15153           (void)NewBR;
15154           Dest = FalseBB;
15155
15156           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15157                                     Cond.getOperand(0), Cond.getOperand(1));
15158           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15159           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15160           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15161                               Chain, Dest, CC, Cmp);
15162           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15163           Cond = Cmp;
15164           addTest = false;
15165         }
15166       }
15167     } else if (Cond.getOpcode() == ISD::SETCC &&
15168                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15169       // For FCMP_UNE, we can emit
15170       // two branches instead of an explicit AND instruction with a
15171       // separate test. However, we only do this if this block doesn't
15172       // have a fall-through edge, because this requires an explicit
15173       // jmp when the condition is false.
15174       if (Op.getNode()->hasOneUse()) {
15175         SDNode *User = *Op.getNode()->use_begin();
15176         // Look for an unconditional branch following this conditional branch.
15177         // We need this because we need to reverse the successors in order
15178         // to implement FCMP_UNE.
15179         if (User->getOpcode() == ISD::BR) {
15180           SDValue FalseBB = User->getOperand(1);
15181           SDNode *NewBR =
15182             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15183           assert(NewBR == User);
15184           (void)NewBR;
15185
15186           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15187                                     Cond.getOperand(0), Cond.getOperand(1));
15188           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15189           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15190           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15191                               Chain, Dest, CC, Cmp);
15192           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15193           Cond = Cmp;
15194           addTest = false;
15195           Dest = FalseBB;
15196         }
15197       }
15198     }
15199   }
15200
15201   if (addTest) {
15202     // Look pass the truncate if the high bits are known zero.
15203     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15204         Cond = Cond.getOperand(0);
15205
15206     // We know the result of AND is compared against zero. Try to match
15207     // it to BT.
15208     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15209       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15210       if (NewSetCC.getNode()) {
15211         CC = NewSetCC.getOperand(0);
15212         Cond = NewSetCC.getOperand(1);
15213         addTest = false;
15214       }
15215     }
15216   }
15217
15218   if (addTest) {
15219     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15220     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15221     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15222   }
15223   Cond = ConvertCmpIfNecessary(Cond, DAG);
15224   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15225                      Chain, Dest, CC, Cond);
15226 }
15227
15228 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15229 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15230 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15231 // that the guard pages used by the OS virtual memory manager are allocated in
15232 // correct sequence.
15233 SDValue
15234 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15235                                            SelectionDAG &DAG) const {
15236   MachineFunction &MF = DAG.getMachineFunction();
15237   bool SplitStack = MF.shouldSplitStack();
15238   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15239                SplitStack;
15240   SDLoc dl(Op);
15241
15242   if (!Lower) {
15243     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15244     SDNode* Node = Op.getNode();
15245
15246     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15247     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15248         " not tell us which reg is the stack pointer!");
15249     EVT VT = Node->getValueType(0);
15250     SDValue Tmp1 = SDValue(Node, 0);
15251     SDValue Tmp2 = SDValue(Node, 1);
15252     SDValue Tmp3 = Node->getOperand(2);
15253     SDValue Chain = Tmp1.getOperand(0);
15254
15255     // Chain the dynamic stack allocation so that it doesn't modify the stack
15256     // pointer when other instructions are using the stack.
15257     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15258         SDLoc(Node));
15259
15260     SDValue Size = Tmp2.getOperand(1);
15261     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15262     Chain = SP.getValue(1);
15263     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15264     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15265     unsigned StackAlign = TFI.getStackAlignment();
15266     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15267     if (Align > StackAlign)
15268       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15269           DAG.getConstant(-(uint64_t)Align, dl, VT));
15270     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15271
15272     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15273         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15274         SDLoc(Node));
15275
15276     SDValue Ops[2] = { Tmp1, Tmp2 };
15277     return DAG.getMergeValues(Ops, dl);
15278   }
15279
15280   // Get the inputs.
15281   SDValue Chain = Op.getOperand(0);
15282   SDValue Size  = Op.getOperand(1);
15283   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15284   EVT VT = Op.getNode()->getValueType(0);
15285
15286   bool Is64Bit = Subtarget->is64Bit();
15287   MVT SPTy = getPointerTy(DAG.getDataLayout());
15288
15289   if (SplitStack) {
15290     MachineRegisterInfo &MRI = MF.getRegInfo();
15291
15292     if (Is64Bit) {
15293       // The 64 bit implementation of segmented stacks needs to clobber both r10
15294       // r11. This makes it impossible to use it along with nested parameters.
15295       const Function *F = MF.getFunction();
15296
15297       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15298            I != E; ++I)
15299         if (I->hasNestAttr())
15300           report_fatal_error("Cannot use segmented stacks with functions that "
15301                              "have nested arguments.");
15302     }
15303
15304     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15305     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15306     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15307     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15308                                 DAG.getRegister(Vreg, SPTy));
15309     SDValue Ops1[2] = { Value, Chain };
15310     return DAG.getMergeValues(Ops1, dl);
15311   } else {
15312     SDValue Flag;
15313     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15314
15315     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15316     Flag = Chain.getValue(1);
15317     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15318
15319     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15320
15321     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15322     unsigned SPReg = RegInfo->getStackRegister();
15323     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15324     Chain = SP.getValue(1);
15325
15326     if (Align) {
15327       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15328                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15329       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15330     }
15331
15332     SDValue Ops1[2] = { SP, Chain };
15333     return DAG.getMergeValues(Ops1, dl);
15334   }
15335 }
15336
15337 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15338   MachineFunction &MF = DAG.getMachineFunction();
15339   auto PtrVT = getPointerTy(MF.getDataLayout());
15340   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15341
15342   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15343   SDLoc DL(Op);
15344
15345   if (!Subtarget->is64Bit() ||
15346       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15347     // vastart just stores the address of the VarArgsFrameIndex slot into the
15348     // memory location argument.
15349     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15350     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15351                         MachinePointerInfo(SV), false, false, 0);
15352   }
15353
15354   // __va_list_tag:
15355   //   gp_offset         (0 - 6 * 8)
15356   //   fp_offset         (48 - 48 + 8 * 16)
15357   //   overflow_arg_area (point to parameters coming in memory).
15358   //   reg_save_area
15359   SmallVector<SDValue, 8> MemOps;
15360   SDValue FIN = Op.getOperand(1);
15361   // Store gp_offset
15362   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15363                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15364                                                DL, MVT::i32),
15365                                FIN, MachinePointerInfo(SV), false, false, 0);
15366   MemOps.push_back(Store);
15367
15368   // Store fp_offset
15369   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15370   Store = DAG.getStore(Op.getOperand(0), DL,
15371                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15372                                        MVT::i32),
15373                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15374   MemOps.push_back(Store);
15375
15376   // Store ptr to overflow_arg_area
15377   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15378   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15379   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15380                        MachinePointerInfo(SV, 8),
15381                        false, false, 0);
15382   MemOps.push_back(Store);
15383
15384   // Store ptr to reg_save_area.
15385   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15386       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15387   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15388   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15389       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15390   MemOps.push_back(Store);
15391   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15392 }
15393
15394 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15395   assert(Subtarget->is64Bit() &&
15396          "LowerVAARG only handles 64-bit va_arg!");
15397   assert(Op.getNode()->getNumOperands() == 4);
15398
15399   MachineFunction &MF = DAG.getMachineFunction();
15400   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15401     // The Win64 ABI uses char* instead of a structure.
15402     return DAG.expandVAArg(Op.getNode());
15403
15404   SDValue Chain = Op.getOperand(0);
15405   SDValue SrcPtr = Op.getOperand(1);
15406   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15407   unsigned Align = Op.getConstantOperandVal(3);
15408   SDLoc dl(Op);
15409
15410   EVT ArgVT = Op.getNode()->getValueType(0);
15411   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15412   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15413   uint8_t ArgMode;
15414
15415   // Decide which area this value should be read from.
15416   // TODO: Implement the AMD64 ABI in its entirety. This simple
15417   // selection mechanism works only for the basic types.
15418   if (ArgVT == MVT::f80) {
15419     llvm_unreachable("va_arg for f80 not yet implemented");
15420   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15421     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15422   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15423     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15424   } else {
15425     llvm_unreachable("Unhandled argument type in LowerVAARG");
15426   }
15427
15428   if (ArgMode == 2) {
15429     // Sanity Check: Make sure using fp_offset makes sense.
15430     assert(!Subtarget->useSoftFloat() &&
15431            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15432            Subtarget->hasSSE1());
15433   }
15434
15435   // Insert VAARG_64 node into the DAG
15436   // VAARG_64 returns two values: Variable Argument Address, Chain
15437   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15438                        DAG.getConstant(ArgMode, dl, MVT::i8),
15439                        DAG.getConstant(Align, dl, MVT::i32)};
15440   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15441   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15442                                           VTs, InstOps, MVT::i64,
15443                                           MachinePointerInfo(SV),
15444                                           /*Align=*/0,
15445                                           /*Volatile=*/false,
15446                                           /*ReadMem=*/true,
15447                                           /*WriteMem=*/true);
15448   Chain = VAARG.getValue(1);
15449
15450   // Load the next argument and return it
15451   return DAG.getLoad(ArgVT, dl,
15452                      Chain,
15453                      VAARG,
15454                      MachinePointerInfo(),
15455                      false, false, false, 0);
15456 }
15457
15458 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15459                            SelectionDAG &DAG) {
15460   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15461   // where a va_list is still an i8*.
15462   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15463   if (Subtarget->isCallingConvWin64(
15464         DAG.getMachineFunction().getFunction()->getCallingConv()))
15465     // Probably a Win64 va_copy.
15466     return DAG.expandVACopy(Op.getNode());
15467
15468   SDValue Chain = Op.getOperand(0);
15469   SDValue DstPtr = Op.getOperand(1);
15470   SDValue SrcPtr = Op.getOperand(2);
15471   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15472   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15473   SDLoc DL(Op);
15474
15475   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15476                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15477                        false, false,
15478                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15479 }
15480
15481 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15482 // amount is a constant. Takes immediate version of shift as input.
15483 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15484                                           SDValue SrcOp, uint64_t ShiftAmt,
15485                                           SelectionDAG &DAG) {
15486   MVT ElementType = VT.getVectorElementType();
15487
15488   // Fold this packed shift into its first operand if ShiftAmt is 0.
15489   if (ShiftAmt == 0)
15490     return SrcOp;
15491
15492   // Check for ShiftAmt >= element width
15493   if (ShiftAmt >= ElementType.getSizeInBits()) {
15494     if (Opc == X86ISD::VSRAI)
15495       ShiftAmt = ElementType.getSizeInBits() - 1;
15496     else
15497       return DAG.getConstant(0, dl, VT);
15498   }
15499
15500   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15501          && "Unknown target vector shift-by-constant node");
15502
15503   // Fold this packed vector shift into a build vector if SrcOp is a
15504   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15505   if (VT == SrcOp.getSimpleValueType() &&
15506       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15507     SmallVector<SDValue, 8> Elts;
15508     unsigned NumElts = SrcOp->getNumOperands();
15509     ConstantSDNode *ND;
15510
15511     switch(Opc) {
15512     default: llvm_unreachable(nullptr);
15513     case X86ISD::VSHLI:
15514       for (unsigned i=0; i!=NumElts; ++i) {
15515         SDValue CurrentOp = SrcOp->getOperand(i);
15516         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15517           Elts.push_back(CurrentOp);
15518           continue;
15519         }
15520         ND = cast<ConstantSDNode>(CurrentOp);
15521         const APInt &C = ND->getAPIntValue();
15522         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15523       }
15524       break;
15525     case X86ISD::VSRLI:
15526       for (unsigned i=0; i!=NumElts; ++i) {
15527         SDValue CurrentOp = SrcOp->getOperand(i);
15528         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15529           Elts.push_back(CurrentOp);
15530           continue;
15531         }
15532         ND = cast<ConstantSDNode>(CurrentOp);
15533         const APInt &C = ND->getAPIntValue();
15534         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15535       }
15536       break;
15537     case X86ISD::VSRAI:
15538       for (unsigned i=0; i!=NumElts; ++i) {
15539         SDValue CurrentOp = SrcOp->getOperand(i);
15540         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15541           Elts.push_back(CurrentOp);
15542           continue;
15543         }
15544         ND = cast<ConstantSDNode>(CurrentOp);
15545         const APInt &C = ND->getAPIntValue();
15546         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15547       }
15548       break;
15549     }
15550
15551     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15552   }
15553
15554   return DAG.getNode(Opc, dl, VT, SrcOp,
15555                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15556 }
15557
15558 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15559 // may or may not be a constant. Takes immediate version of shift as input.
15560 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15561                                    SDValue SrcOp, SDValue ShAmt,
15562                                    SelectionDAG &DAG) {
15563   MVT SVT = ShAmt.getSimpleValueType();
15564   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15565
15566   // Catch shift-by-constant.
15567   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15568     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15569                                       CShAmt->getZExtValue(), DAG);
15570
15571   // Change opcode to non-immediate version
15572   switch (Opc) {
15573     default: llvm_unreachable("Unknown target vector shift node");
15574     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15575     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15576     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15577   }
15578
15579   const X86Subtarget &Subtarget =
15580       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15581   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15582       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15583     // Let the shuffle legalizer expand this shift amount node.
15584     SDValue Op0 = ShAmt.getOperand(0);
15585     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15586     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15587   } else {
15588     // Need to build a vector containing shift amount.
15589     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15590     SmallVector<SDValue, 4> ShOps;
15591     ShOps.push_back(ShAmt);
15592     if (SVT == MVT::i32) {
15593       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15594       ShOps.push_back(DAG.getUNDEF(SVT));
15595     }
15596     ShOps.push_back(DAG.getUNDEF(SVT));
15597
15598     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15599     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15600   }
15601
15602   // The return type has to be a 128-bit type with the same element
15603   // type as the input type.
15604   MVT EltVT = VT.getVectorElementType();
15605   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15606
15607   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15608   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15609 }
15610
15611 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15612 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15613 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15614 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15615                                     SDValue PreservedSrc,
15616                                     const X86Subtarget *Subtarget,
15617                                     SelectionDAG &DAG) {
15618     EVT VT = Op.getValueType();
15619     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15620                                   MVT::i1, VT.getVectorNumElements());
15621     SDValue VMask = SDValue();
15622     unsigned OpcodeSelect = ISD::VSELECT;
15623     SDLoc dl(Op);
15624
15625     assert(MaskVT.isSimple() && "invalid mask type");
15626
15627     if (isAllOnes(Mask))
15628       return Op;
15629
15630     if (MaskVT.bitsGT(Mask.getValueType())) {
15631       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15632                                          MaskVT.getSizeInBits());
15633       VMask = DAG.getBitcast(MaskVT,
15634                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15635     } else {
15636       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15637                                        Mask.getValueType().getSizeInBits());
15638       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15639       // are extracted by EXTRACT_SUBVECTOR.
15640       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15641                           DAG.getBitcast(BitcastVT, Mask),
15642                           DAG.getIntPtrConstant(0, dl));
15643     }
15644
15645     switch (Op.getOpcode()) {
15646       default: break;
15647       case X86ISD::PCMPEQM:
15648       case X86ISD::PCMPGTM:
15649       case X86ISD::CMPM:
15650       case X86ISD::CMPMU:
15651         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15652       case X86ISD::VTRUNC:
15653       case X86ISD::VTRUNCS:
15654       case X86ISD::VTRUNCUS:
15655         // We can't use ISD::VSELECT here because it is not always "Legal"
15656         // for the destination type. For example vpmovqb require only AVX512
15657         // and vselect that can operate on byte element type require BWI
15658         OpcodeSelect = X86ISD::SELECT;
15659         break;
15660     }
15661     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15662       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15663     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15664 }
15665
15666 /// \brief Creates an SDNode for a predicated scalar operation.
15667 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15668 /// The mask is coming as MVT::i8 and it should be truncated
15669 /// to MVT::i1 while lowering masking intrinsics.
15670 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15671 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15672 /// for a scalar instruction.
15673 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15674                                     SDValue PreservedSrc,
15675                                     const X86Subtarget *Subtarget,
15676                                     SelectionDAG &DAG) {
15677     if (isAllOnes(Mask))
15678       return Op;
15679
15680     EVT VT = Op.getValueType();
15681     SDLoc dl(Op);
15682     // The mask should be of type MVT::i1
15683     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15684
15685     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15686       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15687     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15688 }
15689
15690 static int getSEHRegistrationNodeSize(const Function *Fn) {
15691   if (!Fn->hasPersonalityFn())
15692     report_fatal_error(
15693         "querying registration node size for function without personality");
15694   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15695   // WinEHStatePass for the full struct definition.
15696   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15697   case EHPersonality::MSVC_X86SEH: return 24;
15698   case EHPersonality::MSVC_CXX: return 16;
15699   default: break;
15700   }
15701   report_fatal_error("can only recover FP for MSVC EH personality functions");
15702 }
15703
15704 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15705 /// function or when returning to a parent frame after catching an exception, we
15706 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15707 /// Here's the math:
15708 ///   RegNodeBase = EntryEBP - RegNodeSize
15709 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15710 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15711 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15712 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15713                                    SDValue EntryEBP) {
15714   MachineFunction &MF = DAG.getMachineFunction();
15715   SDLoc dl;
15716
15717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15718   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15719
15720   // It's possible that the parent function no longer has a personality function
15721   // if the exceptional code was optimized away, in which case we just return
15722   // the incoming EBP.
15723   if (!Fn->hasPersonalityFn())
15724     return EntryEBP;
15725
15726   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15727
15728   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15729   // registration.
15730   MCSymbol *OffsetSym =
15731       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15732           GlobalValue::getRealLinkageName(Fn->getName()));
15733   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15734   SDValue RegNodeFrameOffset =
15735       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15736
15737   // RegNodeBase = EntryEBP - RegNodeSize
15738   // ParentFP = RegNodeBase - RegNodeFrameOffset
15739   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15740                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15741   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15742 }
15743
15744 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15745                                        SelectionDAG &DAG) {
15746   SDLoc dl(Op);
15747   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15748   EVT VT = Op.getValueType();
15749   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15750   if (IntrData) {
15751     switch(IntrData->Type) {
15752     case INTR_TYPE_1OP:
15753       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15754     case INTR_TYPE_2OP:
15755       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15756         Op.getOperand(2));
15757     case INTR_TYPE_2OP_IMM8:
15758       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15759                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15760     case INTR_TYPE_3OP:
15761       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15762         Op.getOperand(2), Op.getOperand(3));
15763     case INTR_TYPE_4OP:
15764       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15765         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15766     case INTR_TYPE_1OP_MASK_RM: {
15767       SDValue Src = Op.getOperand(1);
15768       SDValue PassThru = Op.getOperand(2);
15769       SDValue Mask = Op.getOperand(3);
15770       SDValue RoundingMode;
15771       // We allways add rounding mode to the Node.
15772       // If the rounding mode is not specified, we add the
15773       // "current direction" mode.
15774       if (Op.getNumOperands() == 4)
15775         RoundingMode =
15776           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15777       else
15778         RoundingMode = Op.getOperand(4);
15779       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15780       if (IntrWithRoundingModeOpcode != 0)
15781         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15782             X86::STATIC_ROUNDING::CUR_DIRECTION)
15783           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15784                                       dl, Op.getValueType(), Src, RoundingMode),
15785                                       Mask, PassThru, Subtarget, DAG);
15786       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15787                                               RoundingMode),
15788                                   Mask, PassThru, Subtarget, DAG);
15789     }
15790     case INTR_TYPE_1OP_MASK: {
15791       SDValue Src = Op.getOperand(1);
15792       SDValue PassThru = Op.getOperand(2);
15793       SDValue Mask = Op.getOperand(3);
15794       // We add rounding mode to the Node when
15795       //   - RM Opcode is specified and
15796       //   - RM is not "current direction".
15797       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15798       if (IntrWithRoundingModeOpcode != 0) {
15799         SDValue Rnd = Op.getOperand(4);
15800         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15801         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15802           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15803                                       dl, Op.getValueType(),
15804                                       Src, Rnd),
15805                                       Mask, PassThru, Subtarget, DAG);
15806         }
15807       }
15808       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15809                                   Mask, PassThru, Subtarget, DAG);
15810     }
15811     case INTR_TYPE_SCALAR_MASK_RM: {
15812       SDValue Src1 = Op.getOperand(1);
15813       SDValue Src2 = Op.getOperand(2);
15814       SDValue Src0 = Op.getOperand(3);
15815       SDValue Mask = Op.getOperand(4);
15816       // There are 2 kinds of intrinsics in this group:
15817       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15818       // (2) With rounding mode and sae - 7 operands.
15819       if (Op.getNumOperands() == 6) {
15820         SDValue Sae  = Op.getOperand(5);
15821         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15822         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15823                                                 Sae),
15824                                     Mask, Src0, Subtarget, DAG);
15825       }
15826       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15827       SDValue RoundingMode  = Op.getOperand(5);
15828       SDValue Sae  = Op.getOperand(6);
15829       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15830                                               RoundingMode, Sae),
15831                                   Mask, Src0, Subtarget, DAG);
15832     }
15833     case INTR_TYPE_2OP_MASK: {
15834       SDValue Src1 = Op.getOperand(1);
15835       SDValue Src2 = Op.getOperand(2);
15836       SDValue PassThru = Op.getOperand(3);
15837       SDValue Mask = Op.getOperand(4);
15838       // We specify 2 possible opcodes for intrinsics with rounding modes.
15839       // First, we check if the intrinsic may have non-default rounding mode,
15840       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15841       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15842       if (IntrWithRoundingModeOpcode != 0) {
15843         SDValue Rnd = Op.getOperand(5);
15844         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15845         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15846           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15847                                       dl, Op.getValueType(),
15848                                       Src1, Src2, Rnd),
15849                                       Mask, PassThru, Subtarget, DAG);
15850         }
15851       }
15852       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15853                                               Src1,Src2),
15854                                   Mask, PassThru, Subtarget, DAG);
15855     }
15856     case INTR_TYPE_2OP_MASK_RM: {
15857       SDValue Src1 = Op.getOperand(1);
15858       SDValue Src2 = Op.getOperand(2);
15859       SDValue PassThru = Op.getOperand(3);
15860       SDValue Mask = Op.getOperand(4);
15861       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15862       // First, we check if the intrinsic have rounding mode (6 operands),
15863       // if not, we set rounding mode to "current".
15864       SDValue Rnd;
15865       if (Op.getNumOperands() == 6)
15866         Rnd = Op.getOperand(5);
15867       else
15868         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15869       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15870                                               Src1, Src2, Rnd),
15871                                   Mask, PassThru, Subtarget, DAG);
15872     }
15873     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15874       SDValue Src1 = Op.getOperand(1);
15875       SDValue Src2 = Op.getOperand(2);
15876       SDValue Src3 = Op.getOperand(3);
15877       SDValue PassThru = Op.getOperand(4);
15878       SDValue Mask = Op.getOperand(5);
15879       SDValue Sae  = Op.getOperand(6);
15880
15881       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15882                                               Src2, Src3, Sae),
15883                                   Mask, PassThru, Subtarget, DAG);
15884     }
15885     case INTR_TYPE_3OP_MASK_RM: {
15886       SDValue Src1 = Op.getOperand(1);
15887       SDValue Src2 = Op.getOperand(2);
15888       SDValue Imm = Op.getOperand(3);
15889       SDValue PassThru = Op.getOperand(4);
15890       SDValue Mask = Op.getOperand(5);
15891       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15892       // First, we check if the intrinsic have rounding mode (7 operands),
15893       // if not, we set rounding mode to "current".
15894       SDValue Rnd;
15895       if (Op.getNumOperands() == 7)
15896         Rnd = Op.getOperand(6);
15897       else
15898         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15899       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15900         Src1, Src2, Imm, Rnd),
15901         Mask, PassThru, Subtarget, DAG);
15902     }
15903     case INTR_TYPE_3OP_IMM8_MASK:
15904     case INTR_TYPE_3OP_MASK: {
15905       SDValue Src1 = Op.getOperand(1);
15906       SDValue Src2 = Op.getOperand(2);
15907       SDValue Src3 = Op.getOperand(3);
15908       SDValue PassThru = Op.getOperand(4);
15909       SDValue Mask = Op.getOperand(5);
15910
15911       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15912         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15913       // We specify 2 possible opcodes for intrinsics with rounding modes.
15914       // First, we check if the intrinsic may have non-default rounding mode,
15915       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15916       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15917       if (IntrWithRoundingModeOpcode != 0) {
15918         SDValue Rnd = Op.getOperand(6);
15919         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15920         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15921           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15922                                       dl, Op.getValueType(),
15923                                       Src1, Src2, Src3, Rnd),
15924                                       Mask, PassThru, Subtarget, DAG);
15925         }
15926       }
15927       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15928                                               Src1, Src2, Src3),
15929                                   Mask, PassThru, Subtarget, DAG);
15930     }
15931     case VPERM_3OP_MASKZ:
15932     case VPERM_3OP_MASK:
15933     case FMA_OP_MASK3:
15934     case FMA_OP_MASKZ:
15935     case FMA_OP_MASK: {
15936       SDValue Src1 = Op.getOperand(1);
15937       SDValue Src2 = Op.getOperand(2);
15938       SDValue Src3 = Op.getOperand(3);
15939       SDValue Mask = Op.getOperand(4);
15940       EVT VT = Op.getValueType();
15941       SDValue PassThru = SDValue();
15942
15943       // set PassThru element
15944       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15945         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15946       else if (IntrData->Type == FMA_OP_MASK3)
15947         PassThru = Src3;
15948       else
15949         PassThru = Src1;
15950
15951       // We specify 2 possible opcodes for intrinsics with rounding modes.
15952       // First, we check if the intrinsic may have non-default rounding mode,
15953       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15954       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15955       if (IntrWithRoundingModeOpcode != 0) {
15956         SDValue Rnd = Op.getOperand(5);
15957         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15958             X86::STATIC_ROUNDING::CUR_DIRECTION)
15959           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15960                                                   dl, Op.getValueType(),
15961                                                   Src1, Src2, Src3, Rnd),
15962                                       Mask, PassThru, Subtarget, DAG);
15963       }
15964       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15965                                               dl, Op.getValueType(),
15966                                               Src1, Src2, Src3),
15967                                   Mask, PassThru, Subtarget, DAG);
15968     }
15969     case CMP_MASK:
15970     case CMP_MASK_CC: {
15971       // Comparison intrinsics with masks.
15972       // Example of transformation:
15973       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15974       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15975       // (i8 (bitcast
15976       //   (v8i1 (insert_subvector undef,
15977       //           (v2i1 (and (PCMPEQM %a, %b),
15978       //                      (extract_subvector
15979       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15980       EVT VT = Op.getOperand(1).getValueType();
15981       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15982                                     VT.getVectorNumElements());
15983       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15984       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15985                                        Mask.getValueType().getSizeInBits());
15986       SDValue Cmp;
15987       if (IntrData->Type == CMP_MASK_CC) {
15988         SDValue CC = Op.getOperand(3);
15989         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15990         // We specify 2 possible opcodes for intrinsics with rounding modes.
15991         // First, we check if the intrinsic may have non-default rounding mode,
15992         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15993         if (IntrData->Opc1 != 0) {
15994           SDValue Rnd = Op.getOperand(5);
15995           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15996               X86::STATIC_ROUNDING::CUR_DIRECTION)
15997             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15998                               Op.getOperand(2), CC, Rnd);
15999         }
16000         //default rounding mode
16001         if(!Cmp.getNode())
16002             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16003                               Op.getOperand(2), CC);
16004
16005       } else {
16006         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16007         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16008                           Op.getOperand(2));
16009       }
16010       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16011                                              DAG.getTargetConstant(0, dl,
16012                                                                    MaskVT),
16013                                              Subtarget, DAG);
16014       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16015                                 DAG.getUNDEF(BitcastVT), CmpMask,
16016                                 DAG.getIntPtrConstant(0, dl));
16017       return DAG.getBitcast(Op.getValueType(), Res);
16018     }
16019     case COMI: { // Comparison intrinsics
16020       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16021       SDValue LHS = Op.getOperand(1);
16022       SDValue RHS = Op.getOperand(2);
16023       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16024       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16025       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16026       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16027                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16028       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16029     }
16030     case VSHIFT:
16031       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16032                                  Op.getOperand(1), Op.getOperand(2), DAG);
16033     case VSHIFT_MASK:
16034       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16035                                                       Op.getSimpleValueType(),
16036                                                       Op.getOperand(1),
16037                                                       Op.getOperand(2), DAG),
16038                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16039                                   DAG);
16040     case COMPRESS_EXPAND_IN_REG: {
16041       SDValue Mask = Op.getOperand(3);
16042       SDValue DataToCompress = Op.getOperand(1);
16043       SDValue PassThru = Op.getOperand(2);
16044       if (isAllOnes(Mask)) // return data as is
16045         return Op.getOperand(1);
16046
16047       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16048                                               DataToCompress),
16049                                   Mask, PassThru, Subtarget, DAG);
16050     }
16051     case BLEND: {
16052       SDValue Mask = Op.getOperand(3);
16053       EVT VT = Op.getValueType();
16054       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16055                                     VT.getVectorNumElements());
16056       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16057                                        Mask.getValueType().getSizeInBits());
16058       SDLoc dl(Op);
16059       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16060                                   DAG.getBitcast(BitcastVT, Mask),
16061                                   DAG.getIntPtrConstant(0, dl));
16062       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16063                          Op.getOperand(2));
16064     }
16065     default:
16066       break;
16067     }
16068   }
16069
16070   switch (IntNo) {
16071   default: return SDValue();    // Don't custom lower most intrinsics.
16072
16073   case Intrinsic::x86_avx2_permd:
16074   case Intrinsic::x86_avx2_permps:
16075     // Operands intentionally swapped. Mask is last operand to intrinsic,
16076     // but second operand for node/instruction.
16077     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16078                        Op.getOperand(2), Op.getOperand(1));
16079
16080   // ptest and testp intrinsics. The intrinsic these come from are designed to
16081   // return an integer value, not just an instruction so lower it to the ptest
16082   // or testp pattern and a setcc for the result.
16083   case Intrinsic::x86_sse41_ptestz:
16084   case Intrinsic::x86_sse41_ptestc:
16085   case Intrinsic::x86_sse41_ptestnzc:
16086   case Intrinsic::x86_avx_ptestz_256:
16087   case Intrinsic::x86_avx_ptestc_256:
16088   case Intrinsic::x86_avx_ptestnzc_256:
16089   case Intrinsic::x86_avx_vtestz_ps:
16090   case Intrinsic::x86_avx_vtestc_ps:
16091   case Intrinsic::x86_avx_vtestnzc_ps:
16092   case Intrinsic::x86_avx_vtestz_pd:
16093   case Intrinsic::x86_avx_vtestc_pd:
16094   case Intrinsic::x86_avx_vtestnzc_pd:
16095   case Intrinsic::x86_avx_vtestz_ps_256:
16096   case Intrinsic::x86_avx_vtestc_ps_256:
16097   case Intrinsic::x86_avx_vtestnzc_ps_256:
16098   case Intrinsic::x86_avx_vtestz_pd_256:
16099   case Intrinsic::x86_avx_vtestc_pd_256:
16100   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16101     bool IsTestPacked = false;
16102     unsigned X86CC;
16103     switch (IntNo) {
16104     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16105     case Intrinsic::x86_avx_vtestz_ps:
16106     case Intrinsic::x86_avx_vtestz_pd:
16107     case Intrinsic::x86_avx_vtestz_ps_256:
16108     case Intrinsic::x86_avx_vtestz_pd_256:
16109       IsTestPacked = true; // Fallthrough
16110     case Intrinsic::x86_sse41_ptestz:
16111     case Intrinsic::x86_avx_ptestz_256:
16112       // ZF = 1
16113       X86CC = X86::COND_E;
16114       break;
16115     case Intrinsic::x86_avx_vtestc_ps:
16116     case Intrinsic::x86_avx_vtestc_pd:
16117     case Intrinsic::x86_avx_vtestc_ps_256:
16118     case Intrinsic::x86_avx_vtestc_pd_256:
16119       IsTestPacked = true; // Fallthrough
16120     case Intrinsic::x86_sse41_ptestc:
16121     case Intrinsic::x86_avx_ptestc_256:
16122       // CF = 1
16123       X86CC = X86::COND_B;
16124       break;
16125     case Intrinsic::x86_avx_vtestnzc_ps:
16126     case Intrinsic::x86_avx_vtestnzc_pd:
16127     case Intrinsic::x86_avx_vtestnzc_ps_256:
16128     case Intrinsic::x86_avx_vtestnzc_pd_256:
16129       IsTestPacked = true; // Fallthrough
16130     case Intrinsic::x86_sse41_ptestnzc:
16131     case Intrinsic::x86_avx_ptestnzc_256:
16132       // ZF and CF = 0
16133       X86CC = X86::COND_A;
16134       break;
16135     }
16136
16137     SDValue LHS = Op.getOperand(1);
16138     SDValue RHS = Op.getOperand(2);
16139     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16140     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16141     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16142     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16143     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16144   }
16145   case Intrinsic::x86_avx512_kortestz_w:
16146   case Intrinsic::x86_avx512_kortestc_w: {
16147     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16148     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16149     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16150     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16151     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16152     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16153     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16154   }
16155
16156   case Intrinsic::x86_sse42_pcmpistria128:
16157   case Intrinsic::x86_sse42_pcmpestria128:
16158   case Intrinsic::x86_sse42_pcmpistric128:
16159   case Intrinsic::x86_sse42_pcmpestric128:
16160   case Intrinsic::x86_sse42_pcmpistrio128:
16161   case Intrinsic::x86_sse42_pcmpestrio128:
16162   case Intrinsic::x86_sse42_pcmpistris128:
16163   case Intrinsic::x86_sse42_pcmpestris128:
16164   case Intrinsic::x86_sse42_pcmpistriz128:
16165   case Intrinsic::x86_sse42_pcmpestriz128: {
16166     unsigned Opcode;
16167     unsigned X86CC;
16168     switch (IntNo) {
16169     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16170     case Intrinsic::x86_sse42_pcmpistria128:
16171       Opcode = X86ISD::PCMPISTRI;
16172       X86CC = X86::COND_A;
16173       break;
16174     case Intrinsic::x86_sse42_pcmpestria128:
16175       Opcode = X86ISD::PCMPESTRI;
16176       X86CC = X86::COND_A;
16177       break;
16178     case Intrinsic::x86_sse42_pcmpistric128:
16179       Opcode = X86ISD::PCMPISTRI;
16180       X86CC = X86::COND_B;
16181       break;
16182     case Intrinsic::x86_sse42_pcmpestric128:
16183       Opcode = X86ISD::PCMPESTRI;
16184       X86CC = X86::COND_B;
16185       break;
16186     case Intrinsic::x86_sse42_pcmpistrio128:
16187       Opcode = X86ISD::PCMPISTRI;
16188       X86CC = X86::COND_O;
16189       break;
16190     case Intrinsic::x86_sse42_pcmpestrio128:
16191       Opcode = X86ISD::PCMPESTRI;
16192       X86CC = X86::COND_O;
16193       break;
16194     case Intrinsic::x86_sse42_pcmpistris128:
16195       Opcode = X86ISD::PCMPISTRI;
16196       X86CC = X86::COND_S;
16197       break;
16198     case Intrinsic::x86_sse42_pcmpestris128:
16199       Opcode = X86ISD::PCMPESTRI;
16200       X86CC = X86::COND_S;
16201       break;
16202     case Intrinsic::x86_sse42_pcmpistriz128:
16203       Opcode = X86ISD::PCMPISTRI;
16204       X86CC = X86::COND_E;
16205       break;
16206     case Intrinsic::x86_sse42_pcmpestriz128:
16207       Opcode = X86ISD::PCMPESTRI;
16208       X86CC = X86::COND_E;
16209       break;
16210     }
16211     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16212     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16213     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16214     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16215                                 DAG.getConstant(X86CC, dl, MVT::i8),
16216                                 SDValue(PCMP.getNode(), 1));
16217     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16218   }
16219
16220   case Intrinsic::x86_sse42_pcmpistri128:
16221   case Intrinsic::x86_sse42_pcmpestri128: {
16222     unsigned Opcode;
16223     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16224       Opcode = X86ISD::PCMPISTRI;
16225     else
16226       Opcode = X86ISD::PCMPESTRI;
16227
16228     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16229     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16230     return DAG.getNode(Opcode, dl, VTs, NewOps);
16231   }
16232
16233   case Intrinsic::x86_seh_lsda: {
16234     // Compute the symbol for the LSDA. We know it'll get emitted later.
16235     MachineFunction &MF = DAG.getMachineFunction();
16236     SDValue Op1 = Op.getOperand(1);
16237     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16238     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16239         GlobalValue::getRealLinkageName(Fn->getName()));
16240
16241     // Generate a simple absolute symbol reference. This intrinsic is only
16242     // supported on 32-bit Windows, which isn't PIC.
16243     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16244     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16245   }
16246
16247   case Intrinsic::x86_seh_recoverfp: {
16248     SDValue FnOp = Op.getOperand(1);
16249     SDValue IncomingFPOp = Op.getOperand(2);
16250     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16251     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16252     if (!Fn)
16253       report_fatal_error(
16254           "llvm.x86.seh.recoverfp must take a function as the first argument");
16255     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16256   }
16257
16258   case Intrinsic::localaddress: {
16259     // Returns one of the stack, base, or frame pointer registers, depending on
16260     // which is used to reference local variables.
16261     MachineFunction &MF = DAG.getMachineFunction();
16262     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16263     unsigned Reg;
16264     if (RegInfo->hasBasePointer(MF))
16265       Reg = RegInfo->getBaseRegister();
16266     else // This function handles the SP or FP case.
16267       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16268     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16269   }
16270   }
16271 }
16272
16273 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16274                               SDValue Src, SDValue Mask, SDValue Base,
16275                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16276                               const X86Subtarget * Subtarget) {
16277   SDLoc dl(Op);
16278   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16279   if (!C)
16280     llvm_unreachable("Invalid scale type");
16281   unsigned ScaleVal = C->getZExtValue();
16282   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16283     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16284
16285   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16286   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16287                              Index.getSimpleValueType().getVectorNumElements());
16288   SDValue MaskInReg;
16289   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16290   if (MaskC)
16291     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16292   else {
16293     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16294                                      Mask.getValueType().getSizeInBits());
16295
16296     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16297     // are extracted by EXTRACT_SUBVECTOR.
16298     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16299                             DAG.getBitcast(BitcastVT, Mask),
16300                             DAG.getIntPtrConstant(0, dl));
16301   }
16302   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16303   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16304   SDValue Segment = DAG.getRegister(0, MVT::i32);
16305   if (Src.getOpcode() == ISD::UNDEF)
16306     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16307   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16308   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16309   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16310   return DAG.getMergeValues(RetOps, dl);
16311 }
16312
16313 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16314                                SDValue Src, SDValue Mask, SDValue Base,
16315                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16316   SDLoc dl(Op);
16317   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16318   if (!C)
16319     llvm_unreachable("Invalid scale type");
16320   unsigned ScaleVal = C->getZExtValue();
16321   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16322     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16323
16324   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16325   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16326   SDValue Segment = DAG.getRegister(0, MVT::i32);
16327   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16328                              Index.getSimpleValueType().getVectorNumElements());
16329   SDValue MaskInReg;
16330   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16331   if (MaskC)
16332     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16333   else {
16334     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16335                                      Mask.getValueType().getSizeInBits());
16336
16337     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16338     // are extracted by EXTRACT_SUBVECTOR.
16339     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16340                             DAG.getBitcast(BitcastVT, Mask),
16341                             DAG.getIntPtrConstant(0, dl));
16342   }
16343   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16344   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16345   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16346   return SDValue(Res, 1);
16347 }
16348
16349 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16350                                SDValue Mask, SDValue Base, SDValue Index,
16351                                SDValue ScaleOp, SDValue Chain) {
16352   SDLoc dl(Op);
16353   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16354   assert(C && "Invalid scale type");
16355   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16356   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16357   SDValue Segment = DAG.getRegister(0, MVT::i32);
16358   EVT MaskVT =
16359     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16360   SDValue MaskInReg;
16361   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16362   if (MaskC)
16363     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16364   else
16365     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16366   //SDVTList VTs = DAG.getVTList(MVT::Other);
16367   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16368   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16369   return SDValue(Res, 0);
16370 }
16371
16372 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16373 // read performance monitor counters (x86_rdpmc).
16374 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16375                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16376                               SmallVectorImpl<SDValue> &Results) {
16377   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16378   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16379   SDValue LO, HI;
16380
16381   // The ECX register is used to select the index of the performance counter
16382   // to read.
16383   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16384                                    N->getOperand(2));
16385   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16386
16387   // Reads the content of a 64-bit performance counter and returns it in the
16388   // registers EDX:EAX.
16389   if (Subtarget->is64Bit()) {
16390     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16391     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16392                             LO.getValue(2));
16393   } else {
16394     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16395     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16396                             LO.getValue(2));
16397   }
16398   Chain = HI.getValue(1);
16399
16400   if (Subtarget->is64Bit()) {
16401     // The EAX register is loaded with the low-order 32 bits. The EDX register
16402     // is loaded with the supported high-order bits of the counter.
16403     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16404                               DAG.getConstant(32, DL, MVT::i8));
16405     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16406     Results.push_back(Chain);
16407     return;
16408   }
16409
16410   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16411   SDValue Ops[] = { LO, HI };
16412   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16413   Results.push_back(Pair);
16414   Results.push_back(Chain);
16415 }
16416
16417 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16418 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16419 // also used to custom lower READCYCLECOUNTER nodes.
16420 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16421                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16422                               SmallVectorImpl<SDValue> &Results) {
16423   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16424   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16425   SDValue LO, HI;
16426
16427   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16428   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16429   // and the EAX register is loaded with the low-order 32 bits.
16430   if (Subtarget->is64Bit()) {
16431     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16432     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16433                             LO.getValue(2));
16434   } else {
16435     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16436     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16437                             LO.getValue(2));
16438   }
16439   SDValue Chain = HI.getValue(1);
16440
16441   if (Opcode == X86ISD::RDTSCP_DAG) {
16442     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16443
16444     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16445     // the ECX register. Add 'ecx' explicitly to the chain.
16446     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16447                                      HI.getValue(2));
16448     // Explicitly store the content of ECX at the location passed in input
16449     // to the 'rdtscp' intrinsic.
16450     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16451                          MachinePointerInfo(), false, false, 0);
16452   }
16453
16454   if (Subtarget->is64Bit()) {
16455     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16456     // the EAX register is loaded with the low-order 32 bits.
16457     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16458                               DAG.getConstant(32, DL, MVT::i8));
16459     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16460     Results.push_back(Chain);
16461     return;
16462   }
16463
16464   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16465   SDValue Ops[] = { LO, HI };
16466   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16467   Results.push_back(Pair);
16468   Results.push_back(Chain);
16469 }
16470
16471 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16472                                      SelectionDAG &DAG) {
16473   SmallVector<SDValue, 2> Results;
16474   SDLoc DL(Op);
16475   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16476                           Results);
16477   return DAG.getMergeValues(Results, DL);
16478 }
16479
16480 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16481                                     SelectionDAG &DAG) {
16482   MachineFunction &MF = DAG.getMachineFunction();
16483   const Function *Fn = MF.getFunction();
16484   SDLoc dl(Op);
16485   SDValue Chain = Op.getOperand(0);
16486
16487   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16488          "using llvm.x86.seh.restoreframe requires a frame pointer");
16489
16490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16491   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16492
16493   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16494   unsigned FrameReg =
16495       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16496   unsigned SPReg = RegInfo->getStackRegister();
16497   unsigned SlotSize = RegInfo->getSlotSize();
16498
16499   // Get incoming EBP.
16500   SDValue IncomingEBP =
16501       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16502
16503   // SP is saved in the first field of every registration node, so load
16504   // [EBP-RegNodeSize] into SP.
16505   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16506   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16507                                DAG.getConstant(-RegNodeSize, dl, VT));
16508   SDValue NewSP =
16509       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16510                   false, VT.getScalarSizeInBits() / 8);
16511   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16512
16513   if (!RegInfo->needsStackRealignment(MF)) {
16514     // Adjust EBP to point back to the original frame position.
16515     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16516     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16517   } else {
16518     assert(RegInfo->hasBasePointer(MF) &&
16519            "functions with Win32 EH must use frame or base pointer register");
16520
16521     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16522     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16523     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16524
16525     // Reload the spilled EBP value, now that the stack and base pointers are
16526     // set up.
16527     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16528     X86FI->setHasSEHFramePtrSave(true);
16529     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16530     X86FI->setSEHFramePtrSaveIndex(FI);
16531     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16532                                 MachinePointerInfo(), false, false, false,
16533                                 VT.getScalarSizeInBits() / 8);
16534     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16535   }
16536
16537   return Chain;
16538 }
16539
16540 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16541 /// return truncate Store/MaskedStore Node
16542 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16543                                                SelectionDAG &DAG,
16544                                                MVT ElementType) {
16545   SDLoc dl(Op);
16546   SDValue Mask = Op.getOperand(4);
16547   SDValue DataToTruncate = Op.getOperand(3);
16548   SDValue Addr = Op.getOperand(2);
16549   SDValue Chain = Op.getOperand(0);
16550
16551   EVT VT  = DataToTruncate.getValueType();
16552   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16553                              ElementType, VT.getVectorNumElements());
16554
16555   if (isAllOnes(Mask)) // return just a truncate store
16556     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16557                              MachinePointerInfo(), SVT, false, false,
16558                              SVT.getScalarSizeInBits()/8);
16559
16560   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16561                                 MVT::i1, VT.getVectorNumElements());
16562   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16563                                    Mask.getValueType().getSizeInBits());
16564   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16565   // are extracted by EXTRACT_SUBVECTOR.
16566   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16567                               DAG.getBitcast(BitcastVT, Mask),
16568                               DAG.getIntPtrConstant(0, dl));
16569
16570   MachineMemOperand *MMO = DAG.getMachineFunction().
16571     getMachineMemOperand(MachinePointerInfo(),
16572                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16573                          SVT.getScalarSizeInBits()/8);
16574
16575   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16576                             VMask, SVT, MMO, true);
16577 }
16578
16579 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16580                                       SelectionDAG &DAG) {
16581   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16582
16583   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16584   if (!IntrData) {
16585     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16586       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16587     return SDValue();
16588   }
16589
16590   SDLoc dl(Op);
16591   switch(IntrData->Type) {
16592   default:
16593     llvm_unreachable("Unknown Intrinsic Type");
16594     break;
16595   case RDSEED:
16596   case RDRAND: {
16597     // Emit the node with the right value type.
16598     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16599     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16600
16601     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16602     // Otherwise return the value from Rand, which is always 0, casted to i32.
16603     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16604                       DAG.getConstant(1, dl, Op->getValueType(1)),
16605                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16606                       SDValue(Result.getNode(), 1) };
16607     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16608                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16609                                   Ops);
16610
16611     // Return { result, isValid, chain }.
16612     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16613                        SDValue(Result.getNode(), 2));
16614   }
16615   case GATHER: {
16616   //gather(v1, mask, index, base, scale);
16617     SDValue Chain = Op.getOperand(0);
16618     SDValue Src   = Op.getOperand(2);
16619     SDValue Base  = Op.getOperand(3);
16620     SDValue Index = Op.getOperand(4);
16621     SDValue Mask  = Op.getOperand(5);
16622     SDValue Scale = Op.getOperand(6);
16623     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16624                          Chain, Subtarget);
16625   }
16626   case SCATTER: {
16627   //scatter(base, mask, index, v1, scale);
16628     SDValue Chain = Op.getOperand(0);
16629     SDValue Base  = Op.getOperand(2);
16630     SDValue Mask  = Op.getOperand(3);
16631     SDValue Index = Op.getOperand(4);
16632     SDValue Src   = Op.getOperand(5);
16633     SDValue Scale = Op.getOperand(6);
16634     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16635                           Scale, Chain);
16636   }
16637   case PREFETCH: {
16638     SDValue Hint = Op.getOperand(6);
16639     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16640     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16641     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16642     SDValue Chain = Op.getOperand(0);
16643     SDValue Mask  = Op.getOperand(2);
16644     SDValue Index = Op.getOperand(3);
16645     SDValue Base  = Op.getOperand(4);
16646     SDValue Scale = Op.getOperand(5);
16647     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16648   }
16649   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16650   case RDTSC: {
16651     SmallVector<SDValue, 2> Results;
16652     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16653                             Results);
16654     return DAG.getMergeValues(Results, dl);
16655   }
16656   // Read Performance Monitoring Counters.
16657   case RDPMC: {
16658     SmallVector<SDValue, 2> Results;
16659     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16660     return DAG.getMergeValues(Results, dl);
16661   }
16662   // XTEST intrinsics.
16663   case XTEST: {
16664     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16665     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16666     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16667                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16668                                 InTrans);
16669     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16670     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16671                        Ret, SDValue(InTrans.getNode(), 1));
16672   }
16673   // ADC/ADCX/SBB
16674   case ADX: {
16675     SmallVector<SDValue, 2> Results;
16676     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16677     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16678     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16679                                 DAG.getConstant(-1, dl, MVT::i8));
16680     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16681                               Op.getOperand(4), GenCF.getValue(1));
16682     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16683                                  Op.getOperand(5), MachinePointerInfo(),
16684                                  false, false, 0);
16685     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16686                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16687                                 Res.getValue(1));
16688     Results.push_back(SetCC);
16689     Results.push_back(Store);
16690     return DAG.getMergeValues(Results, dl);
16691   }
16692   case COMPRESS_TO_MEM: {
16693     SDLoc dl(Op);
16694     SDValue Mask = Op.getOperand(4);
16695     SDValue DataToCompress = Op.getOperand(3);
16696     SDValue Addr = Op.getOperand(2);
16697     SDValue Chain = Op.getOperand(0);
16698
16699     EVT VT = DataToCompress.getValueType();
16700     if (isAllOnes(Mask)) // return just a store
16701       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16702                           MachinePointerInfo(), false, false,
16703                           VT.getScalarSizeInBits()/8);
16704
16705     SDValue Compressed =
16706       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16707                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16708     return DAG.getStore(Chain, dl, Compressed, Addr,
16709                         MachinePointerInfo(), false, false,
16710                         VT.getScalarSizeInBits()/8);
16711   }
16712   case TRUNCATE_TO_MEM_VI8:
16713     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16714   case TRUNCATE_TO_MEM_VI16:
16715     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16716   case TRUNCATE_TO_MEM_VI32:
16717     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16718   case EXPAND_FROM_MEM: {
16719     SDLoc dl(Op);
16720     SDValue Mask = Op.getOperand(4);
16721     SDValue PassThru = Op.getOperand(3);
16722     SDValue Addr = Op.getOperand(2);
16723     SDValue Chain = Op.getOperand(0);
16724     EVT VT = Op.getValueType();
16725
16726     if (isAllOnes(Mask)) // return just a load
16727       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16728                          false, VT.getScalarSizeInBits()/8);
16729
16730     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16731                                        false, false, false,
16732                                        VT.getScalarSizeInBits()/8);
16733
16734     SDValue Results[] = {
16735       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16736                            Mask, PassThru, Subtarget, DAG), Chain};
16737     return DAG.getMergeValues(Results, dl);
16738   }
16739   }
16740 }
16741
16742 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16743                                            SelectionDAG &DAG) const {
16744   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16745   MFI->setReturnAddressIsTaken(true);
16746
16747   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16748     return SDValue();
16749
16750   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16751   SDLoc dl(Op);
16752   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16753
16754   if (Depth > 0) {
16755     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16756     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16757     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16758     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16759                        DAG.getNode(ISD::ADD, dl, PtrVT,
16760                                    FrameAddr, Offset),
16761                        MachinePointerInfo(), false, false, false, 0);
16762   }
16763
16764   // Just load the return address.
16765   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16766   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16767                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16768 }
16769
16770 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16771   MachineFunction &MF = DAG.getMachineFunction();
16772   MachineFrameInfo *MFI = MF.getFrameInfo();
16773   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16774   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16775   EVT VT = Op.getValueType();
16776
16777   MFI->setFrameAddressIsTaken(true);
16778
16779   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16780     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16781     // is not possible to crawl up the stack without looking at the unwind codes
16782     // simultaneously.
16783     int FrameAddrIndex = FuncInfo->getFAIndex();
16784     if (!FrameAddrIndex) {
16785       // Set up a frame object for the return address.
16786       unsigned SlotSize = RegInfo->getSlotSize();
16787       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16788           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16789       FuncInfo->setFAIndex(FrameAddrIndex);
16790     }
16791     return DAG.getFrameIndex(FrameAddrIndex, VT);
16792   }
16793
16794   unsigned FrameReg =
16795       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16796   SDLoc dl(Op);  // FIXME probably not meaningful
16797   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16798   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16799           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16800          "Invalid Frame Register!");
16801   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16802   while (Depth--)
16803     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16804                             MachinePointerInfo(),
16805                             false, false, false, 0);
16806   return FrameAddr;
16807 }
16808
16809 // FIXME? Maybe this could be a TableGen attribute on some registers and
16810 // this table could be generated automatically from RegInfo.
16811 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16812                                               SelectionDAG &DAG) const {
16813   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16814   const MachineFunction &MF = DAG.getMachineFunction();
16815
16816   unsigned Reg = StringSwitch<unsigned>(RegName)
16817                        .Case("esp", X86::ESP)
16818                        .Case("rsp", X86::RSP)
16819                        .Case("ebp", X86::EBP)
16820                        .Case("rbp", X86::RBP)
16821                        .Default(0);
16822
16823   if (Reg == X86::EBP || Reg == X86::RBP) {
16824     if (!TFI.hasFP(MF))
16825       report_fatal_error("register " + StringRef(RegName) +
16826                          " is allocatable: function has no frame pointer");
16827 #ifndef NDEBUG
16828     else {
16829       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16830       unsigned FrameReg =
16831           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16832       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16833              "Invalid Frame Register!");
16834     }
16835 #endif
16836   }
16837
16838   if (Reg)
16839     return Reg;
16840
16841   report_fatal_error("Invalid register name global variable");
16842 }
16843
16844 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16845                                                      SelectionDAG &DAG) const {
16846   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16847   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16848 }
16849
16850 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16851   SDValue Chain     = Op.getOperand(0);
16852   SDValue Offset    = Op.getOperand(1);
16853   SDValue Handler   = Op.getOperand(2);
16854   SDLoc dl      (Op);
16855
16856   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16857   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16858   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16859   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16860           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16861          "Invalid Frame Register!");
16862   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16863   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16864
16865   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16866                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16867                                                        dl));
16868   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16869   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16870                        false, false, 0);
16871   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16872
16873   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16874                      DAG.getRegister(StoreAddrReg, PtrVT));
16875 }
16876
16877 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16878   SDValue Chain = Op.getOperand(0);
16879   SDValue Dest = Op.getOperand(1);
16880   SDLoc DL(Op);
16881
16882   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16883
16884   MachineFunction &MF = DAG.getMachineFunction();
16885   if (isAsynchronousEHPersonality(
16886           classifyEHPersonality(MF.getFunction()->getPersonalityFn()))) {
16887     // For SEH, codegen catchret as a branch for now.
16888     // FIXME: Insert something to restore the frame.
16889     return DAG.getNode(ISD::BR, DL, MVT::Other, Chain, Dest);
16890   }
16891
16892
16893   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16894
16895   // Load the address of the destination block.
16896   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16897   SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16898   unsigned WrapperKind =
16899       Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16900   SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16901   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16902   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16903                      DAG.getRegister(ReturnReg, PtrVT));
16904 }
16905
16906 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16907                                                SelectionDAG &DAG) const {
16908   SDLoc DL(Op);
16909   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16910                      DAG.getVTList(MVT::i32, MVT::Other),
16911                      Op.getOperand(0), Op.getOperand(1));
16912 }
16913
16914 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16915                                                 SelectionDAG &DAG) const {
16916   SDLoc DL(Op);
16917   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16918                      Op.getOperand(0), Op.getOperand(1));
16919 }
16920
16921 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16922   return Op.getOperand(0);
16923 }
16924
16925 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16926                                                 SelectionDAG &DAG) const {
16927   SDValue Root = Op.getOperand(0);
16928   SDValue Trmp = Op.getOperand(1); // trampoline
16929   SDValue FPtr = Op.getOperand(2); // nested function
16930   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16931   SDLoc dl (Op);
16932
16933   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16934   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16935
16936   if (Subtarget->is64Bit()) {
16937     SDValue OutChains[6];
16938
16939     // Large code-model.
16940     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16941     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16942
16943     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16944     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16945
16946     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16947
16948     // Load the pointer to the nested function into R11.
16949     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16950     SDValue Addr = Trmp;
16951     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16952                                 Addr, MachinePointerInfo(TrmpAddr),
16953                                 false, false, 0);
16954
16955     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16956                        DAG.getConstant(2, dl, MVT::i64));
16957     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16958                                 MachinePointerInfo(TrmpAddr, 2),
16959                                 false, false, 2);
16960
16961     // Load the 'nest' parameter value into R10.
16962     // R10 is specified in X86CallingConv.td
16963     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16964     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16965                        DAG.getConstant(10, dl, MVT::i64));
16966     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16967                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16968                                 false, false, 0);
16969
16970     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16971                        DAG.getConstant(12, dl, MVT::i64));
16972     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16973                                 MachinePointerInfo(TrmpAddr, 12),
16974                                 false, false, 2);
16975
16976     // Jump to the nested function.
16977     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16978     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16979                        DAG.getConstant(20, dl, MVT::i64));
16980     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16981                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16982                                 false, false, 0);
16983
16984     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16985     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16986                        DAG.getConstant(22, dl, MVT::i64));
16987     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16988                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16989                                 false, false, 0);
16990
16991     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16992   } else {
16993     const Function *Func =
16994       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16995     CallingConv::ID CC = Func->getCallingConv();
16996     unsigned NestReg;
16997
16998     switch (CC) {
16999     default:
17000       llvm_unreachable("Unsupported calling convention");
17001     case CallingConv::C:
17002     case CallingConv::X86_StdCall: {
17003       // Pass 'nest' parameter in ECX.
17004       // Must be kept in sync with X86CallingConv.td
17005       NestReg = X86::ECX;
17006
17007       // Check that ECX wasn't needed by an 'inreg' parameter.
17008       FunctionType *FTy = Func->getFunctionType();
17009       const AttributeSet &Attrs = Func->getAttributes();
17010
17011       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17012         unsigned InRegCount = 0;
17013         unsigned Idx = 1;
17014
17015         for (FunctionType::param_iterator I = FTy->param_begin(),
17016              E = FTy->param_end(); I != E; ++I, ++Idx)
17017           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17018             auto &DL = DAG.getDataLayout();
17019             // FIXME: should only count parameters that are lowered to integers.
17020             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17021           }
17022
17023         if (InRegCount > 2) {
17024           report_fatal_error("Nest register in use - reduce number of inreg"
17025                              " parameters!");
17026         }
17027       }
17028       break;
17029     }
17030     case CallingConv::X86_FastCall:
17031     case CallingConv::X86_ThisCall:
17032     case CallingConv::Fast:
17033       // Pass 'nest' parameter in EAX.
17034       // Must be kept in sync with X86CallingConv.td
17035       NestReg = X86::EAX;
17036       break;
17037     }
17038
17039     SDValue OutChains[4];
17040     SDValue Addr, Disp;
17041
17042     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17043                        DAG.getConstant(10, dl, MVT::i32));
17044     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17045
17046     // This is storing the opcode for MOV32ri.
17047     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17048     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17049     OutChains[0] = DAG.getStore(Root, dl,
17050                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17051                                 Trmp, MachinePointerInfo(TrmpAddr),
17052                                 false, false, 0);
17053
17054     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17055                        DAG.getConstant(1, dl, MVT::i32));
17056     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17057                                 MachinePointerInfo(TrmpAddr, 1),
17058                                 false, false, 1);
17059
17060     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17061     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17062                        DAG.getConstant(5, dl, MVT::i32));
17063     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17064                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17065                                 false, false, 1);
17066
17067     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17068                        DAG.getConstant(6, dl, MVT::i32));
17069     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17070                                 MachinePointerInfo(TrmpAddr, 6),
17071                                 false, false, 1);
17072
17073     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17074   }
17075 }
17076
17077 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17078                                             SelectionDAG &DAG) const {
17079   /*
17080    The rounding mode is in bits 11:10 of FPSR, and has the following
17081    settings:
17082      00 Round to nearest
17083      01 Round to -inf
17084      10 Round to +inf
17085      11 Round to 0
17086
17087   FLT_ROUNDS, on the other hand, expects the following:
17088     -1 Undefined
17089      0 Round to 0
17090      1 Round to nearest
17091      2 Round to +inf
17092      3 Round to -inf
17093
17094   To perform the conversion, we do:
17095     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17096   */
17097
17098   MachineFunction &MF = DAG.getMachineFunction();
17099   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17100   unsigned StackAlignment = TFI.getStackAlignment();
17101   MVT VT = Op.getSimpleValueType();
17102   SDLoc DL(Op);
17103
17104   // Save FP Control Word to stack slot
17105   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17106   SDValue StackSlot =
17107       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17108
17109   MachineMemOperand *MMO =
17110       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17111                               MachineMemOperand::MOStore, 2, 2);
17112
17113   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17114   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17115                                           DAG.getVTList(MVT::Other),
17116                                           Ops, MVT::i16, MMO);
17117
17118   // Load FP Control Word from stack slot
17119   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17120                             MachinePointerInfo(), false, false, false, 0);
17121
17122   // Transform as necessary
17123   SDValue CWD1 =
17124     DAG.getNode(ISD::SRL, DL, MVT::i16,
17125                 DAG.getNode(ISD::AND, DL, MVT::i16,
17126                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17127                 DAG.getConstant(11, DL, MVT::i8));
17128   SDValue CWD2 =
17129     DAG.getNode(ISD::SRL, DL, MVT::i16,
17130                 DAG.getNode(ISD::AND, DL, MVT::i16,
17131                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17132                 DAG.getConstant(9, DL, MVT::i8));
17133
17134   SDValue RetVal =
17135     DAG.getNode(ISD::AND, DL, MVT::i16,
17136                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17137                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17138                             DAG.getConstant(1, DL, MVT::i16)),
17139                 DAG.getConstant(3, DL, MVT::i16));
17140
17141   return DAG.getNode((VT.getSizeInBits() < 16 ?
17142                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17143 }
17144
17145 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17146   MVT VT = Op.getSimpleValueType();
17147   EVT OpVT = VT;
17148   unsigned NumBits = VT.getSizeInBits();
17149   SDLoc dl(Op);
17150
17151   Op = Op.getOperand(0);
17152   if (VT == MVT::i8) {
17153     // Zero extend to i32 since there is not an i8 bsr.
17154     OpVT = MVT::i32;
17155     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17156   }
17157
17158   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17159   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17160   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17161
17162   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17163   SDValue Ops[] = {
17164     Op,
17165     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17166     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17167     Op.getValue(1)
17168   };
17169   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17170
17171   // Finally xor with NumBits-1.
17172   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17173                    DAG.getConstant(NumBits - 1, dl, OpVT));
17174
17175   if (VT == MVT::i8)
17176     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17177   return Op;
17178 }
17179
17180 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17181   MVT VT = Op.getSimpleValueType();
17182   EVT OpVT = VT;
17183   unsigned NumBits = VT.getSizeInBits();
17184   SDLoc dl(Op);
17185
17186   Op = Op.getOperand(0);
17187   if (VT == MVT::i8) {
17188     // Zero extend to i32 since there is not an i8 bsr.
17189     OpVT = MVT::i32;
17190     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17191   }
17192
17193   // Issue a bsr (scan bits in reverse).
17194   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17195   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17196
17197   // And xor with NumBits-1.
17198   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17199                    DAG.getConstant(NumBits - 1, dl, OpVT));
17200
17201   if (VT == MVT::i8)
17202     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17203   return Op;
17204 }
17205
17206 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17207   MVT VT = Op.getSimpleValueType();
17208   unsigned NumBits = VT.getSizeInBits();
17209   SDLoc dl(Op);
17210   Op = Op.getOperand(0);
17211
17212   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17213   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17214   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17215
17216   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17217   SDValue Ops[] = {
17218     Op,
17219     DAG.getConstant(NumBits, dl, VT),
17220     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17221     Op.getValue(1)
17222   };
17223   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17224 }
17225
17226 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17227 // ones, and then concatenate the result back.
17228 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17229   MVT VT = Op.getSimpleValueType();
17230
17231   assert(VT.is256BitVector() && VT.isInteger() &&
17232          "Unsupported value type for operation");
17233
17234   unsigned NumElems = VT.getVectorNumElements();
17235   SDLoc dl(Op);
17236
17237   // Extract the LHS vectors
17238   SDValue LHS = Op.getOperand(0);
17239   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17240   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17241
17242   // Extract the RHS vectors
17243   SDValue RHS = Op.getOperand(1);
17244   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17245   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17246
17247   MVT EltVT = VT.getVectorElementType();
17248   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17249
17250   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17251                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17252                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17253 }
17254
17255 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17256   if (Op.getValueType() == MVT::i1)
17257     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17258                        Op.getOperand(0), Op.getOperand(1));
17259   assert(Op.getSimpleValueType().is256BitVector() &&
17260          Op.getSimpleValueType().isInteger() &&
17261          "Only handle AVX 256-bit vector integer operation");
17262   return Lower256IntArith(Op, DAG);
17263 }
17264
17265 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17266   if (Op.getValueType() == MVT::i1)
17267     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17268                        Op.getOperand(0), Op.getOperand(1));
17269   assert(Op.getSimpleValueType().is256BitVector() &&
17270          Op.getSimpleValueType().isInteger() &&
17271          "Only handle AVX 256-bit vector integer operation");
17272   return Lower256IntArith(Op, DAG);
17273 }
17274
17275 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17276   assert(Op.getSimpleValueType().is256BitVector() &&
17277          Op.getSimpleValueType().isInteger() &&
17278          "Only handle AVX 256-bit vector integer operation");
17279   return Lower256IntArith(Op, DAG);
17280 }
17281
17282 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17283                         SelectionDAG &DAG) {
17284   SDLoc dl(Op);
17285   MVT VT = Op.getSimpleValueType();
17286
17287   if (VT == MVT::i1)
17288     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17289
17290   // Decompose 256-bit ops into smaller 128-bit ops.
17291   if (VT.is256BitVector() && !Subtarget->hasInt256())
17292     return Lower256IntArith(Op, DAG);
17293
17294   SDValue A = Op.getOperand(0);
17295   SDValue B = Op.getOperand(1);
17296
17297   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17298   // pairs, multiply and truncate.
17299   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17300     if (Subtarget->hasInt256()) {
17301       if (VT == MVT::v32i8) {
17302         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17303         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17304         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17305         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17306         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17307         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17308         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17309         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17310                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17311                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17312       }
17313
17314       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17315       return DAG.getNode(
17316           ISD::TRUNCATE, dl, VT,
17317           DAG.getNode(ISD::MUL, dl, ExVT,
17318                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17319                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17320     }
17321
17322     assert(VT == MVT::v16i8 &&
17323            "Pre-AVX2 support only supports v16i8 multiplication");
17324     MVT ExVT = MVT::v8i16;
17325
17326     // Extract the lo parts and sign extend to i16
17327     SDValue ALo, BLo;
17328     if (Subtarget->hasSSE41()) {
17329       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17330       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17331     } else {
17332       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17333                               -1, 4, -1, 5, -1, 6, -1, 7};
17334       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17335       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17336       ALo = DAG.getBitcast(ExVT, ALo);
17337       BLo = DAG.getBitcast(ExVT, BLo);
17338       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17339       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17340     }
17341
17342     // Extract the hi parts and sign extend to i16
17343     SDValue AHi, BHi;
17344     if (Subtarget->hasSSE41()) {
17345       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17346                               -1, -1, -1, -1, -1, -1, -1, -1};
17347       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17348       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17349       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17350       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17351     } else {
17352       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17353                               -1, 12, -1, 13, -1, 14, -1, 15};
17354       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17355       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17356       AHi = DAG.getBitcast(ExVT, AHi);
17357       BHi = DAG.getBitcast(ExVT, BHi);
17358       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17359       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17360     }
17361
17362     // Multiply, mask the lower 8bits of the lo/hi results and pack
17363     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17364     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17365     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17366     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17367     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17368   }
17369
17370   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17371   if (VT == MVT::v4i32) {
17372     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17373            "Should not custom lower when pmuldq is available!");
17374
17375     // Extract the odd parts.
17376     static const int UnpackMask[] = { 1, -1, 3, -1 };
17377     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17378     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17379
17380     // Multiply the even parts.
17381     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17382     // Now multiply odd parts.
17383     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17384
17385     Evens = DAG.getBitcast(VT, Evens);
17386     Odds = DAG.getBitcast(VT, Odds);
17387
17388     // Merge the two vectors back together with a shuffle. This expands into 2
17389     // shuffles.
17390     static const int ShufMask[] = { 0, 4, 2, 6 };
17391     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17392   }
17393
17394   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17395          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17396
17397   //  Ahi = psrlqi(a, 32);
17398   //  Bhi = psrlqi(b, 32);
17399   //
17400   //  AloBlo = pmuludq(a, b);
17401   //  AloBhi = pmuludq(a, Bhi);
17402   //  AhiBlo = pmuludq(Ahi, b);
17403
17404   //  AloBhi = psllqi(AloBhi, 32);
17405   //  AhiBlo = psllqi(AhiBlo, 32);
17406   //  return AloBlo + AloBhi + AhiBlo;
17407
17408   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17409   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17410
17411   SDValue AhiBlo = Ahi;
17412   SDValue AloBhi = Bhi;
17413   // Bit cast to 32-bit vectors for MULUDQ
17414   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17415                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17416   A = DAG.getBitcast(MulVT, A);
17417   B = DAG.getBitcast(MulVT, B);
17418   Ahi = DAG.getBitcast(MulVT, Ahi);
17419   Bhi = DAG.getBitcast(MulVT, Bhi);
17420
17421   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17422   // After shifting right const values the result may be all-zero.
17423   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17424     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17425     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17426   }
17427   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17428     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17429     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17430   }
17431
17432   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17433   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17434 }
17435
17436 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17437   assert(Subtarget->isTargetWin64() && "Unexpected target");
17438   EVT VT = Op.getValueType();
17439   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17440          "Unexpected return type for lowering");
17441
17442   RTLIB::Libcall LC;
17443   bool isSigned;
17444   switch (Op->getOpcode()) {
17445   default: llvm_unreachable("Unexpected request for libcall!");
17446   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17447   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17448   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17449   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17450   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17451   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17452   }
17453
17454   SDLoc dl(Op);
17455   SDValue InChain = DAG.getEntryNode();
17456
17457   TargetLowering::ArgListTy Args;
17458   TargetLowering::ArgListEntry Entry;
17459   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17460     EVT ArgVT = Op->getOperand(i).getValueType();
17461     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17462            "Unexpected argument type for lowering");
17463     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17464     Entry.Node = StackPtr;
17465     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17466                            false, false, 16);
17467     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17468     Entry.Ty = PointerType::get(ArgTy,0);
17469     Entry.isSExt = false;
17470     Entry.isZExt = false;
17471     Args.push_back(Entry);
17472   }
17473
17474   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17475                                          getPointerTy(DAG.getDataLayout()));
17476
17477   TargetLowering::CallLoweringInfo CLI(DAG);
17478   CLI.setDebugLoc(dl).setChain(InChain)
17479     .setCallee(getLibcallCallingConv(LC),
17480                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17481                Callee, std::move(Args), 0)
17482     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17483
17484   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17485   return DAG.getBitcast(VT, CallInfo.first);
17486 }
17487
17488 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17489                              SelectionDAG &DAG) {
17490   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17491   EVT VT = Op0.getValueType();
17492   SDLoc dl(Op);
17493
17494   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17495          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17496
17497   // PMULxD operations multiply each even value (starting at 0) of LHS with
17498   // the related value of RHS and produce a widen result.
17499   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17500   // => <2 x i64> <ae|cg>
17501   //
17502   // In other word, to have all the results, we need to perform two PMULxD:
17503   // 1. one with the even values.
17504   // 2. one with the odd values.
17505   // To achieve #2, with need to place the odd values at an even position.
17506   //
17507   // Place the odd value at an even position (basically, shift all values 1
17508   // step to the left):
17509   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17510   // <a|b|c|d> => <b|undef|d|undef>
17511   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17512   // <e|f|g|h> => <f|undef|h|undef>
17513   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17514
17515   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17516   // ints.
17517   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17518   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17519   unsigned Opcode =
17520       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17521   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17522   // => <2 x i64> <ae|cg>
17523   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17524   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17525   // => <2 x i64> <bf|dh>
17526   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17527
17528   // Shuffle it back into the right order.
17529   SDValue Highs, Lows;
17530   if (VT == MVT::v8i32) {
17531     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17532     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17533     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17534     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17535   } else {
17536     const int HighMask[] = {1, 5, 3, 7};
17537     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17538     const int LowMask[] = {0, 4, 2, 6};
17539     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17540   }
17541
17542   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17543   // unsigned multiply.
17544   if (IsSigned && !Subtarget->hasSSE41()) {
17545     SDValue ShAmt = DAG.getConstant(
17546         31, dl,
17547         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17548     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17549                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17550     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17551                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17552
17553     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17554     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17555   }
17556
17557   // The first result of MUL_LOHI is actually the low value, followed by the
17558   // high value.
17559   SDValue Ops[] = {Lows, Highs};
17560   return DAG.getMergeValues(Ops, dl);
17561 }
17562
17563 // Return true if the required (according to Opcode) shift-imm form is natively
17564 // supported by the Subtarget
17565 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17566                                         unsigned Opcode) {
17567   if (VT.getScalarSizeInBits() < 16)
17568     return false;
17569
17570   if (VT.is512BitVector() &&
17571       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17572     return true;
17573
17574   bool LShift = VT.is128BitVector() ||
17575     (VT.is256BitVector() && Subtarget->hasInt256());
17576
17577   bool AShift = LShift && (Subtarget->hasVLX() ||
17578     (VT != MVT::v2i64 && VT != MVT::v4i64));
17579   return (Opcode == ISD::SRA) ? AShift : LShift;
17580 }
17581
17582 // The shift amount is a variable, but it is the same for all vector lanes.
17583 // These instructions are defined together with shift-immediate.
17584 static
17585 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17586                                       unsigned Opcode) {
17587   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17588 }
17589
17590 // Return true if the required (according to Opcode) variable-shift form is
17591 // natively supported by the Subtarget
17592 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17593                                     unsigned Opcode) {
17594
17595   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17596     return false;
17597
17598   // vXi16 supported only on AVX-512, BWI
17599   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17600     return false;
17601
17602   if (VT.is512BitVector() || Subtarget->hasVLX())
17603     return true;
17604
17605   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17606   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17607   return (Opcode == ISD::SRA) ? AShift : LShift;
17608 }
17609
17610 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17611                                          const X86Subtarget *Subtarget) {
17612   MVT VT = Op.getSimpleValueType();
17613   SDLoc dl(Op);
17614   SDValue R = Op.getOperand(0);
17615   SDValue Amt = Op.getOperand(1);
17616
17617   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17618     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17619
17620   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17621     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17622     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17623     SDValue Ex = DAG.getBitcast(ExVT, R);
17624
17625     if (ShiftAmt >= 32) {
17626       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17627       SDValue Upper =
17628           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17629       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17630                                                  ShiftAmt - 32, DAG);
17631       if (VT == MVT::v2i64)
17632         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17633       if (VT == MVT::v4i64)
17634         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17635                                   {9, 1, 11, 3, 13, 5, 15, 7});
17636     } else {
17637       // SRA upper i32, SHL whole i64 and select lower i32.
17638       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17639                                                  ShiftAmt, DAG);
17640       SDValue Lower =
17641           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17642       Lower = DAG.getBitcast(ExVT, Lower);
17643       if (VT == MVT::v2i64)
17644         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17645       if (VT == MVT::v4i64)
17646         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17647                                   {8, 1, 10, 3, 12, 5, 14, 7});
17648     }
17649     return DAG.getBitcast(VT, Ex);
17650   };
17651
17652   // Optimize shl/srl/sra with constant shift amount.
17653   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17654     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17655       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17656
17657       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17658         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17659
17660       // i64 SRA needs to be performed as partial shifts.
17661       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17662           Op.getOpcode() == ISD::SRA)
17663         return ArithmeticShiftRight64(ShiftAmt);
17664
17665       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17666         unsigned NumElts = VT.getVectorNumElements();
17667         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17668
17669         if (Op.getOpcode() == ISD::SHL) {
17670           // Simple i8 add case
17671           if (ShiftAmt == 1)
17672             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17673
17674           // Make a large shift.
17675           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17676                                                    R, ShiftAmt, DAG);
17677           SHL = DAG.getBitcast(VT, SHL);
17678           // Zero out the rightmost bits.
17679           SmallVector<SDValue, 32> V(
17680               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17681           return DAG.getNode(ISD::AND, dl, VT, SHL,
17682                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17683         }
17684         if (Op.getOpcode() == ISD::SRL) {
17685           // Make a large shift.
17686           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17687                                                    R, ShiftAmt, DAG);
17688           SRL = DAG.getBitcast(VT, SRL);
17689           // Zero out the leftmost bits.
17690           SmallVector<SDValue, 32> V(
17691               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17692           return DAG.getNode(ISD::AND, dl, VT, SRL,
17693                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17694         }
17695         if (Op.getOpcode() == ISD::SRA) {
17696           if (ShiftAmt == 7) {
17697             // ashr(R, 7)  === cmp_slt(R, 0)
17698             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17699             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17700           }
17701
17702           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17703           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17704           SmallVector<SDValue, 32> V(NumElts,
17705                                      DAG.getConstant(128 >> ShiftAmt, dl,
17706                                                      MVT::i8));
17707           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17708           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17709           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17710           return Res;
17711         }
17712         llvm_unreachable("Unknown shift opcode.");
17713       }
17714     }
17715   }
17716
17717   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17718   if (!Subtarget->is64Bit() &&
17719       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17720
17721     // Peek through any splat that was introduced for i64 shift vectorization.
17722     int SplatIndex = -1;
17723     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17724       if (SVN->isSplat()) {
17725         SplatIndex = SVN->getSplatIndex();
17726         Amt = Amt.getOperand(0);
17727         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17728                "Splat shuffle referencing second operand");
17729       }
17730
17731     if (Amt.getOpcode() != ISD::BITCAST ||
17732         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17733       return SDValue();
17734
17735     Amt = Amt.getOperand(0);
17736     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17737                      VT.getVectorNumElements();
17738     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17739     uint64_t ShiftAmt = 0;
17740     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17741     for (unsigned i = 0; i != Ratio; ++i) {
17742       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17743       if (!C)
17744         return SDValue();
17745       // 6 == Log2(64)
17746       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17747     }
17748
17749     // Check remaining shift amounts (if not a splat).
17750     if (SplatIndex < 0) {
17751       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17752         uint64_t ShAmt = 0;
17753         for (unsigned j = 0; j != Ratio; ++j) {
17754           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17755           if (!C)
17756             return SDValue();
17757           // 6 == Log2(64)
17758           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17759         }
17760         if (ShAmt != ShiftAmt)
17761           return SDValue();
17762       }
17763     }
17764
17765     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17766       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17767
17768     if (Op.getOpcode() == ISD::SRA)
17769       return ArithmeticShiftRight64(ShiftAmt);
17770   }
17771
17772   return SDValue();
17773 }
17774
17775 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17776                                         const X86Subtarget* Subtarget) {
17777   MVT VT = Op.getSimpleValueType();
17778   SDLoc dl(Op);
17779   SDValue R = Op.getOperand(0);
17780   SDValue Amt = Op.getOperand(1);
17781
17782   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17783     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17784
17785   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17786     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17787
17788   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17789     SDValue BaseShAmt;
17790     EVT EltVT = VT.getVectorElementType();
17791
17792     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17793       // Check if this build_vector node is doing a splat.
17794       // If so, then set BaseShAmt equal to the splat value.
17795       BaseShAmt = BV->getSplatValue();
17796       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17797         BaseShAmt = SDValue();
17798     } else {
17799       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17800         Amt = Amt.getOperand(0);
17801
17802       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17803       if (SVN && SVN->isSplat()) {
17804         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17805         SDValue InVec = Amt.getOperand(0);
17806         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17807           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17808                  "Unexpected shuffle index found!");
17809           BaseShAmt = InVec.getOperand(SplatIdx);
17810         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17811            if (ConstantSDNode *C =
17812                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17813              if (C->getZExtValue() == SplatIdx)
17814                BaseShAmt = InVec.getOperand(1);
17815            }
17816         }
17817
17818         if (!BaseShAmt)
17819           // Avoid introducing an extract element from a shuffle.
17820           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17821                                   DAG.getIntPtrConstant(SplatIdx, dl));
17822       }
17823     }
17824
17825     if (BaseShAmt.getNode()) {
17826       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17827       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17828         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17829       else if (EltVT.bitsLT(MVT::i32))
17830         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17831
17832       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17833     }
17834   }
17835
17836   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17837   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17838       Amt.getOpcode() == ISD::BITCAST &&
17839       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17840     Amt = Amt.getOperand(0);
17841     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17842                      VT.getVectorNumElements();
17843     std::vector<SDValue> Vals(Ratio);
17844     for (unsigned i = 0; i != Ratio; ++i)
17845       Vals[i] = Amt.getOperand(i);
17846     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17847       for (unsigned j = 0; j != Ratio; ++j)
17848         if (Vals[j] != Amt.getOperand(i + j))
17849           return SDValue();
17850     }
17851
17852     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17853       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17854   }
17855   return SDValue();
17856 }
17857
17858 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17859                           SelectionDAG &DAG) {
17860   MVT VT = Op.getSimpleValueType();
17861   SDLoc dl(Op);
17862   SDValue R = Op.getOperand(0);
17863   SDValue Amt = Op.getOperand(1);
17864
17865   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17866   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17867
17868   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17869     return V;
17870
17871   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17872       return V;
17873
17874   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17875     return Op;
17876
17877   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17878   // shifts per-lane and then shuffle the partial results back together.
17879   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17880     // Splat the shift amounts so the scalar shifts above will catch it.
17881     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17882     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17883     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17884     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17885     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17886   }
17887
17888   // i64 vector arithmetic shift can be emulated with the transform:
17889   // M = lshr(SIGN_BIT, Amt)
17890   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17891   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17892       Op.getOpcode() == ISD::SRA) {
17893     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17894     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17895     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17896     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17897     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17898     return R;
17899   }
17900
17901   // If possible, lower this packed shift into a vector multiply instead of
17902   // expanding it into a sequence of scalar shifts.
17903   // Do this only if the vector shift count is a constant build_vector.
17904   if (Op.getOpcode() == ISD::SHL &&
17905       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17906        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17907       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17908     SmallVector<SDValue, 8> Elts;
17909     EVT SVT = VT.getScalarType();
17910     unsigned SVTBits = SVT.getSizeInBits();
17911     const APInt &One = APInt(SVTBits, 1);
17912     unsigned NumElems = VT.getVectorNumElements();
17913
17914     for (unsigned i=0; i !=NumElems; ++i) {
17915       SDValue Op = Amt->getOperand(i);
17916       if (Op->getOpcode() == ISD::UNDEF) {
17917         Elts.push_back(Op);
17918         continue;
17919       }
17920
17921       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17922       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17923       uint64_t ShAmt = C.getZExtValue();
17924       if (ShAmt >= SVTBits) {
17925         Elts.push_back(DAG.getUNDEF(SVT));
17926         continue;
17927       }
17928       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17929     }
17930     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17931     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17932   }
17933
17934   // Lower SHL with variable shift amount.
17935   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17936     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17937
17938     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17939                      DAG.getConstant(0x3f800000U, dl, VT));
17940     Op = DAG.getBitcast(MVT::v4f32, Op);
17941     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17942     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17943   }
17944
17945   // If possible, lower this shift as a sequence of two shifts by
17946   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17947   // Example:
17948   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17949   //
17950   // Could be rewritten as:
17951   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17952   //
17953   // The advantage is that the two shifts from the example would be
17954   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17955   // the vector shift into four scalar shifts plus four pairs of vector
17956   // insert/extract.
17957   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17958       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17959     unsigned TargetOpcode = X86ISD::MOVSS;
17960     bool CanBeSimplified;
17961     // The splat value for the first packed shift (the 'X' from the example).
17962     SDValue Amt1 = Amt->getOperand(0);
17963     // The splat value for the second packed shift (the 'Y' from the example).
17964     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17965                                         Amt->getOperand(2);
17966
17967     // See if it is possible to replace this node with a sequence of
17968     // two shifts followed by a MOVSS/MOVSD
17969     if (VT == MVT::v4i32) {
17970       // Check if it is legal to use a MOVSS.
17971       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17972                         Amt2 == Amt->getOperand(3);
17973       if (!CanBeSimplified) {
17974         // Otherwise, check if we can still simplify this node using a MOVSD.
17975         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17976                           Amt->getOperand(2) == Amt->getOperand(3);
17977         TargetOpcode = X86ISD::MOVSD;
17978         Amt2 = Amt->getOperand(2);
17979       }
17980     } else {
17981       // Do similar checks for the case where the machine value type
17982       // is MVT::v8i16.
17983       CanBeSimplified = Amt1 == Amt->getOperand(1);
17984       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17985         CanBeSimplified = Amt2 == Amt->getOperand(i);
17986
17987       if (!CanBeSimplified) {
17988         TargetOpcode = X86ISD::MOVSD;
17989         CanBeSimplified = true;
17990         Amt2 = Amt->getOperand(4);
17991         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17992           CanBeSimplified = Amt1 == Amt->getOperand(i);
17993         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17994           CanBeSimplified = Amt2 == Amt->getOperand(j);
17995       }
17996     }
17997
17998     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17999         isa<ConstantSDNode>(Amt2)) {
18000       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18001       EVT CastVT = MVT::v4i32;
18002       SDValue Splat1 =
18003         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18004       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18005       SDValue Splat2 =
18006         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18007       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18008       if (TargetOpcode == X86ISD::MOVSD)
18009         CastVT = MVT::v2i64;
18010       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18011       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18012       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18013                                             BitCast1, DAG);
18014       return DAG.getBitcast(VT, Result);
18015     }
18016   }
18017
18018   // v4i32 Non Uniform Shifts.
18019   // If the shift amount is constant we can shift each lane using the SSE2
18020   // immediate shifts, else we need to zero-extend each lane to the lower i64
18021   // and shift using the SSE2 variable shifts.
18022   // The separate results can then be blended together.
18023   if (VT == MVT::v4i32) {
18024     unsigned Opc = Op.getOpcode();
18025     SDValue Amt0, Amt1, Amt2, Amt3;
18026     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18027       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18028       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18029       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18030       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18031     } else {
18032       // ISD::SHL is handled above but we include it here for completeness.
18033       switch (Opc) {
18034       default:
18035         llvm_unreachable("Unknown target vector shift node");
18036       case ISD::SHL:
18037         Opc = X86ISD::VSHL;
18038         break;
18039       case ISD::SRL:
18040         Opc = X86ISD::VSRL;
18041         break;
18042       case ISD::SRA:
18043         Opc = X86ISD::VSRA;
18044         break;
18045       }
18046       // The SSE2 shifts use the lower i64 as the same shift amount for
18047       // all lanes and the upper i64 is ignored. These shuffle masks
18048       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18049       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18050       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18051       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18052       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18053       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18054     }
18055
18056     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18057     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18058     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18059     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18060     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18061     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18062     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18063   }
18064
18065   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18066     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18067     unsigned ShiftOpcode = Op->getOpcode();
18068
18069     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18070       // On SSE41 targets we make use of the fact that VSELECT lowers
18071       // to PBLENDVB which selects bytes based just on the sign bit.
18072       if (Subtarget->hasSSE41()) {
18073         V0 = DAG.getBitcast(VT, V0);
18074         V1 = DAG.getBitcast(VT, V1);
18075         Sel = DAG.getBitcast(VT, Sel);
18076         return DAG.getBitcast(SelVT,
18077                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18078       }
18079       // On pre-SSE41 targets we test for the sign bit by comparing to
18080       // zero - a negative value will set all bits of the lanes to true
18081       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18082       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18083       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18084       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18085     };
18086
18087     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18088     // We can safely do this using i16 shifts as we're only interested in
18089     // the 3 lower bits of each byte.
18090     Amt = DAG.getBitcast(ExtVT, Amt);
18091     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18092     Amt = DAG.getBitcast(VT, Amt);
18093
18094     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18095       // r = VSELECT(r, shift(r, 4), a);
18096       SDValue M =
18097           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18098       R = SignBitSelect(VT, Amt, M, R);
18099
18100       // a += a
18101       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18102
18103       // r = VSELECT(r, shift(r, 2), a);
18104       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18105       R = SignBitSelect(VT, Amt, M, R);
18106
18107       // a += a
18108       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18109
18110       // return VSELECT(r, shift(r, 1), a);
18111       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18112       R = SignBitSelect(VT, Amt, M, R);
18113       return R;
18114     }
18115
18116     if (Op->getOpcode() == ISD::SRA) {
18117       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18118       // so we can correctly sign extend. We don't care what happens to the
18119       // lower byte.
18120       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18121       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18122       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18123       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18124       ALo = DAG.getBitcast(ExtVT, ALo);
18125       AHi = DAG.getBitcast(ExtVT, AHi);
18126       RLo = DAG.getBitcast(ExtVT, RLo);
18127       RHi = DAG.getBitcast(ExtVT, RHi);
18128
18129       // r = VSELECT(r, shift(r, 4), a);
18130       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18131                                 DAG.getConstant(4, dl, ExtVT));
18132       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18133                                 DAG.getConstant(4, dl, ExtVT));
18134       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18135       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18136
18137       // a += a
18138       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18139       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18140
18141       // r = VSELECT(r, shift(r, 2), a);
18142       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18143                         DAG.getConstant(2, dl, ExtVT));
18144       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18145                         DAG.getConstant(2, dl, ExtVT));
18146       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18147       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18148
18149       // a += a
18150       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18151       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18152
18153       // r = VSELECT(r, shift(r, 1), a);
18154       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18155                         DAG.getConstant(1, dl, ExtVT));
18156       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18157                         DAG.getConstant(1, dl, ExtVT));
18158       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18159       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18160
18161       // Logical shift the result back to the lower byte, leaving a zero upper
18162       // byte
18163       // meaning that we can safely pack with PACKUSWB.
18164       RLo =
18165           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18166       RHi =
18167           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18168       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18169     }
18170   }
18171
18172   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18173   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18174   // solution better.
18175   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18176     MVT ExtVT = MVT::v8i32;
18177     unsigned ExtOpc =
18178         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18179     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18180     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18181     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18182                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18183   }
18184
18185   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18186     MVT ExtVT = MVT::v8i32;
18187     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18188     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18189     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18190     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18191     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18192     ALo = DAG.getBitcast(ExtVT, ALo);
18193     AHi = DAG.getBitcast(ExtVT, AHi);
18194     RLo = DAG.getBitcast(ExtVT, RLo);
18195     RHi = DAG.getBitcast(ExtVT, RHi);
18196     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18197     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18198     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18199     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18200     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18201   }
18202
18203   if (VT == MVT::v8i16) {
18204     unsigned ShiftOpcode = Op->getOpcode();
18205
18206     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18207       // On SSE41 targets we make use of the fact that VSELECT lowers
18208       // to PBLENDVB which selects bytes based just on the sign bit.
18209       if (Subtarget->hasSSE41()) {
18210         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18211         V0 = DAG.getBitcast(ExtVT, V0);
18212         V1 = DAG.getBitcast(ExtVT, V1);
18213         Sel = DAG.getBitcast(ExtVT, Sel);
18214         return DAG.getBitcast(
18215             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18216       }
18217       // On pre-SSE41 targets we splat the sign bit - a negative value will
18218       // set all bits of the lanes to true and VSELECT uses that in
18219       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18220       SDValue C =
18221           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18222       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18223     };
18224
18225     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18226     if (Subtarget->hasSSE41()) {
18227       // On SSE41 targets we need to replicate the shift mask in both
18228       // bytes for PBLENDVB.
18229       Amt = DAG.getNode(
18230           ISD::OR, dl, VT,
18231           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18232           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18233     } else {
18234       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18235     }
18236
18237     // r = VSELECT(r, shift(r, 8), a);
18238     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18239     R = SignBitSelect(Amt, M, R);
18240
18241     // a += a
18242     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18243
18244     // r = VSELECT(r, shift(r, 4), a);
18245     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18246     R = SignBitSelect(Amt, M, R);
18247
18248     // a += a
18249     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18250
18251     // r = VSELECT(r, shift(r, 2), a);
18252     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18253     R = SignBitSelect(Amt, M, R);
18254
18255     // a += a
18256     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18257
18258     // return VSELECT(r, shift(r, 1), a);
18259     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18260     R = SignBitSelect(Amt, M, R);
18261     return R;
18262   }
18263
18264   // Decompose 256-bit shifts into smaller 128-bit shifts.
18265   if (VT.is256BitVector()) {
18266     unsigned NumElems = VT.getVectorNumElements();
18267     MVT EltVT = VT.getVectorElementType();
18268     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18269
18270     // Extract the two vectors
18271     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18272     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18273
18274     // Recreate the shift amount vectors
18275     SDValue Amt1, Amt2;
18276     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18277       // Constant shift amount
18278       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18279       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18280       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18281
18282       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18283       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18284     } else {
18285       // Variable shift amount
18286       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18287       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18288     }
18289
18290     // Issue new vector shifts for the smaller types
18291     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18292     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18293
18294     // Concatenate the result back
18295     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18296   }
18297
18298   return SDValue();
18299 }
18300
18301 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18302   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18303   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18304   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18305   // has only one use.
18306   SDNode *N = Op.getNode();
18307   SDValue LHS = N->getOperand(0);
18308   SDValue RHS = N->getOperand(1);
18309   unsigned BaseOp = 0;
18310   unsigned Cond = 0;
18311   SDLoc DL(Op);
18312   switch (Op.getOpcode()) {
18313   default: llvm_unreachable("Unknown ovf instruction!");
18314   case ISD::SADDO:
18315     // A subtract of one will be selected as a INC. Note that INC doesn't
18316     // set CF, so we can't do this for UADDO.
18317     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18318       if (C->isOne()) {
18319         BaseOp = X86ISD::INC;
18320         Cond = X86::COND_O;
18321         break;
18322       }
18323     BaseOp = X86ISD::ADD;
18324     Cond = X86::COND_O;
18325     break;
18326   case ISD::UADDO:
18327     BaseOp = X86ISD::ADD;
18328     Cond = X86::COND_B;
18329     break;
18330   case ISD::SSUBO:
18331     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18332     // set CF, so we can't do this for USUBO.
18333     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18334       if (C->isOne()) {
18335         BaseOp = X86ISD::DEC;
18336         Cond = X86::COND_O;
18337         break;
18338       }
18339     BaseOp = X86ISD::SUB;
18340     Cond = X86::COND_O;
18341     break;
18342   case ISD::USUBO:
18343     BaseOp = X86ISD::SUB;
18344     Cond = X86::COND_B;
18345     break;
18346   case ISD::SMULO:
18347     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18348     Cond = X86::COND_O;
18349     break;
18350   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18351     if (N->getValueType(0) == MVT::i8) {
18352       BaseOp = X86ISD::UMUL8;
18353       Cond = X86::COND_O;
18354       break;
18355     }
18356     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18357                                  MVT::i32);
18358     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18359
18360     SDValue SetCC =
18361       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18362                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18363                   SDValue(Sum.getNode(), 2));
18364
18365     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18366   }
18367   }
18368
18369   // Also sets EFLAGS.
18370   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18371   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18372
18373   SDValue SetCC =
18374     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18375                 DAG.getConstant(Cond, DL, MVT::i32),
18376                 SDValue(Sum.getNode(), 1));
18377
18378   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18379 }
18380
18381 /// Returns true if the operand type is exactly twice the native width, and
18382 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18383 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18384 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18385 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18386   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18387
18388   if (OpWidth == 64)
18389     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18390   else if (OpWidth == 128)
18391     return Subtarget->hasCmpxchg16b();
18392   else
18393     return false;
18394 }
18395
18396 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18397   return needsCmpXchgNb(SI->getValueOperand()->getType());
18398 }
18399
18400 // Note: this turns large loads into lock cmpxchg8b/16b.
18401 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18402 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18403   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18404   return needsCmpXchgNb(PTy->getElementType());
18405 }
18406
18407 TargetLoweringBase::AtomicRMWExpansionKind
18408 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18409   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18410   Type *MemType = AI->getType();
18411
18412   // If the operand is too big, we must see if cmpxchg8/16b is available
18413   // and default to library calls otherwise.
18414   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18415     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18416                                    : AtomicRMWExpansionKind::None;
18417   }
18418
18419   AtomicRMWInst::BinOp Op = AI->getOperation();
18420   switch (Op) {
18421   default:
18422     llvm_unreachable("Unknown atomic operation");
18423   case AtomicRMWInst::Xchg:
18424   case AtomicRMWInst::Add:
18425   case AtomicRMWInst::Sub:
18426     // It's better to use xadd, xsub or xchg for these in all cases.
18427     return AtomicRMWExpansionKind::None;
18428   case AtomicRMWInst::Or:
18429   case AtomicRMWInst::And:
18430   case AtomicRMWInst::Xor:
18431     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18432     // prefix to a normal instruction for these operations.
18433     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18434                             : AtomicRMWExpansionKind::None;
18435   case AtomicRMWInst::Nand:
18436   case AtomicRMWInst::Max:
18437   case AtomicRMWInst::Min:
18438   case AtomicRMWInst::UMax:
18439   case AtomicRMWInst::UMin:
18440     // These always require a non-trivial set of data operations on x86. We must
18441     // use a cmpxchg loop.
18442     return AtomicRMWExpansionKind::CmpXChg;
18443   }
18444 }
18445
18446 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18447   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18448   // no-sse2). There isn't any reason to disable it if the target processor
18449   // supports it.
18450   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18451 }
18452
18453 LoadInst *
18454 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18455   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18456   Type *MemType = AI->getType();
18457   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18458   // there is no benefit in turning such RMWs into loads, and it is actually
18459   // harmful as it introduces a mfence.
18460   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18461     return nullptr;
18462
18463   auto Builder = IRBuilder<>(AI);
18464   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18465   auto SynchScope = AI->getSynchScope();
18466   // We must restrict the ordering to avoid generating loads with Release or
18467   // ReleaseAcquire orderings.
18468   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18469   auto Ptr = AI->getPointerOperand();
18470
18471   // Before the load we need a fence. Here is an example lifted from
18472   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18473   // is required:
18474   // Thread 0:
18475   //   x.store(1, relaxed);
18476   //   r1 = y.fetch_add(0, release);
18477   // Thread 1:
18478   //   y.fetch_add(42, acquire);
18479   //   r2 = x.load(relaxed);
18480   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18481   // lowered to just a load without a fence. A mfence flushes the store buffer,
18482   // making the optimization clearly correct.
18483   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18484   // otherwise, we might be able to be more aggressive on relaxed idempotent
18485   // rmw. In practice, they do not look useful, so we don't try to be
18486   // especially clever.
18487   if (SynchScope == SingleThread)
18488     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18489     // the IR level, so we must wrap it in an intrinsic.
18490     return nullptr;
18491
18492   if (!hasMFENCE(*Subtarget))
18493     // FIXME: it might make sense to use a locked operation here but on a
18494     // different cache-line to prevent cache-line bouncing. In practice it
18495     // is probably a small win, and x86 processors without mfence are rare
18496     // enough that we do not bother.
18497     return nullptr;
18498
18499   Function *MFence =
18500       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18501   Builder.CreateCall(MFence, {});
18502
18503   // Finally we can emit the atomic load.
18504   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18505           AI->getType()->getPrimitiveSizeInBits());
18506   Loaded->setAtomic(Order, SynchScope);
18507   AI->replaceAllUsesWith(Loaded);
18508   AI->eraseFromParent();
18509   return Loaded;
18510 }
18511
18512 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18513                                  SelectionDAG &DAG) {
18514   SDLoc dl(Op);
18515   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18516     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18517   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18518     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18519
18520   // The only fence that needs an instruction is a sequentially-consistent
18521   // cross-thread fence.
18522   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18523     if (hasMFENCE(*Subtarget))
18524       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18525
18526     SDValue Chain = Op.getOperand(0);
18527     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18528     SDValue Ops[] = {
18529       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18530       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18531       DAG.getRegister(0, MVT::i32),            // Index
18532       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18533       DAG.getRegister(0, MVT::i32),            // Segment.
18534       Zero,
18535       Chain
18536     };
18537     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18538     return SDValue(Res, 0);
18539   }
18540
18541   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18542   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18543 }
18544
18545 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18546                              SelectionDAG &DAG) {
18547   MVT T = Op.getSimpleValueType();
18548   SDLoc DL(Op);
18549   unsigned Reg = 0;
18550   unsigned size = 0;
18551   switch(T.SimpleTy) {
18552   default: llvm_unreachable("Invalid value type!");
18553   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18554   case MVT::i16: Reg = X86::AX;  size = 2; break;
18555   case MVT::i32: Reg = X86::EAX; size = 4; break;
18556   case MVT::i64:
18557     assert(Subtarget->is64Bit() && "Node not type legal!");
18558     Reg = X86::RAX; size = 8;
18559     break;
18560   }
18561   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18562                                   Op.getOperand(2), SDValue());
18563   SDValue Ops[] = { cpIn.getValue(0),
18564                     Op.getOperand(1),
18565                     Op.getOperand(3),
18566                     DAG.getTargetConstant(size, DL, MVT::i8),
18567                     cpIn.getValue(1) };
18568   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18569   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18570   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18571                                            Ops, T, MMO);
18572
18573   SDValue cpOut =
18574     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18575   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18576                                       MVT::i32, cpOut.getValue(2));
18577   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18578                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18579                                 EFLAGS);
18580
18581   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18582   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18583   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18584   return SDValue();
18585 }
18586
18587 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18588                             SelectionDAG &DAG) {
18589   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18590   MVT DstVT = Op.getSimpleValueType();
18591
18592   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18593     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18594     if (DstVT != MVT::f64)
18595       // This conversion needs to be expanded.
18596       return SDValue();
18597
18598     SDValue InVec = Op->getOperand(0);
18599     SDLoc dl(Op);
18600     unsigned NumElts = SrcVT.getVectorNumElements();
18601     EVT SVT = SrcVT.getVectorElementType();
18602
18603     // Widen the vector in input in the case of MVT::v2i32.
18604     // Example: from MVT::v2i32 to MVT::v4i32.
18605     SmallVector<SDValue, 16> Elts;
18606     for (unsigned i = 0, e = NumElts; i != e; ++i)
18607       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18608                                  DAG.getIntPtrConstant(i, dl)));
18609
18610     // Explicitly mark the extra elements as Undef.
18611     Elts.append(NumElts, DAG.getUNDEF(SVT));
18612
18613     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18614     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18615     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18616     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18617                        DAG.getIntPtrConstant(0, dl));
18618   }
18619
18620   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18621          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18622   assert((DstVT == MVT::i64 ||
18623           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18624          "Unexpected custom BITCAST");
18625   // i64 <=> MMX conversions are Legal.
18626   if (SrcVT==MVT::i64 && DstVT.isVector())
18627     return Op;
18628   if (DstVT==MVT::i64 && SrcVT.isVector())
18629     return Op;
18630   // MMX <=> MMX conversions are Legal.
18631   if (SrcVT.isVector() && DstVT.isVector())
18632     return Op;
18633   // All other conversions need to be expanded.
18634   return SDValue();
18635 }
18636
18637 /// Compute the horizontal sum of bytes in V for the elements of VT.
18638 ///
18639 /// Requires V to be a byte vector and VT to be an integer vector type with
18640 /// wider elements than V's type. The width of the elements of VT determines
18641 /// how many bytes of V are summed horizontally to produce each element of the
18642 /// result.
18643 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18644                                       const X86Subtarget *Subtarget,
18645                                       SelectionDAG &DAG) {
18646   SDLoc DL(V);
18647   MVT ByteVecVT = V.getSimpleValueType();
18648   MVT EltVT = VT.getVectorElementType();
18649   int NumElts = VT.getVectorNumElements();
18650   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18651          "Expected value to have byte element type.");
18652   assert(EltVT != MVT::i8 &&
18653          "Horizontal byte sum only makes sense for wider elements!");
18654   unsigned VecSize = VT.getSizeInBits();
18655   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18656
18657   // PSADBW instruction horizontally add all bytes and leave the result in i64
18658   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18659   if (EltVT == MVT::i64) {
18660     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18661     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18662     return DAG.getBitcast(VT, V);
18663   }
18664
18665   if (EltVT == MVT::i32) {
18666     // We unpack the low half and high half into i32s interleaved with zeros so
18667     // that we can use PSADBW to horizontally sum them. The most useful part of
18668     // this is that it lines up the results of two PSADBW instructions to be
18669     // two v2i64 vectors which concatenated are the 4 population counts. We can
18670     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18671     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18672     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18673     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18674
18675     // Do the horizontal sums into two v2i64s.
18676     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18677     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18678                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18679     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18680                        DAG.getBitcast(ByteVecVT, High), Zeros);
18681
18682     // Merge them together.
18683     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18684     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18685                     DAG.getBitcast(ShortVecVT, Low),
18686                     DAG.getBitcast(ShortVecVT, High));
18687
18688     return DAG.getBitcast(VT, V);
18689   }
18690
18691   // The only element type left is i16.
18692   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18693
18694   // To obtain pop count for each i16 element starting from the pop count for
18695   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18696   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18697   // directly supported.
18698   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18699   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18700   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18701   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18702                   DAG.getBitcast(ByteVecVT, V));
18703   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18704 }
18705
18706 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18707                                         const X86Subtarget *Subtarget,
18708                                         SelectionDAG &DAG) {
18709   MVT VT = Op.getSimpleValueType();
18710   MVT EltVT = VT.getVectorElementType();
18711   unsigned VecSize = VT.getSizeInBits();
18712
18713   // Implement a lookup table in register by using an algorithm based on:
18714   // http://wm.ite.pl/articles/sse-popcount.html
18715   //
18716   // The general idea is that every lower byte nibble in the input vector is an
18717   // index into a in-register pre-computed pop count table. We then split up the
18718   // input vector in two new ones: (1) a vector with only the shifted-right
18719   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18720   // masked out higher ones) for each byte. PSHUB is used separately with both
18721   // to index the in-register table. Next, both are added and the result is a
18722   // i8 vector where each element contains the pop count for input byte.
18723   //
18724   // To obtain the pop count for elements != i8, we follow up with the same
18725   // approach and use additional tricks as described below.
18726   //
18727   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18728                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18729                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18730                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18731
18732   int NumByteElts = VecSize / 8;
18733   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18734   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18735   SmallVector<SDValue, 16> LUTVec;
18736   for (int i = 0; i < NumByteElts; ++i)
18737     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18738   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18739   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18740                                   DAG.getConstant(0x0F, DL, MVT::i8));
18741   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18742
18743   // High nibbles
18744   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18745   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18746   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18747
18748   // Low nibbles
18749   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18750
18751   // The input vector is used as the shuffle mask that index elements into the
18752   // LUT. After counting low and high nibbles, add the vector to obtain the
18753   // final pop count per i8 element.
18754   SDValue HighPopCnt =
18755       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18756   SDValue LowPopCnt =
18757       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18758   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18759
18760   if (EltVT == MVT::i8)
18761     return PopCnt;
18762
18763   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18764 }
18765
18766 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18767                                        const X86Subtarget *Subtarget,
18768                                        SelectionDAG &DAG) {
18769   MVT VT = Op.getSimpleValueType();
18770   assert(VT.is128BitVector() &&
18771          "Only 128-bit vector bitmath lowering supported.");
18772
18773   int VecSize = VT.getSizeInBits();
18774   MVT EltVT = VT.getVectorElementType();
18775   int Len = EltVT.getSizeInBits();
18776
18777   // This is the vectorized version of the "best" algorithm from
18778   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18779   // with a minor tweak to use a series of adds + shifts instead of vector
18780   // multiplications. Implemented for all integer vector types. We only use
18781   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18782   // much faster, even faster than using native popcnt instructions.
18783
18784   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18785     MVT VT = V.getSimpleValueType();
18786     SmallVector<SDValue, 32> Shifters(
18787         VT.getVectorNumElements(),
18788         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18789     return DAG.getNode(OpCode, DL, VT, V,
18790                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18791   };
18792   auto GetMask = [&](SDValue V, APInt Mask) {
18793     MVT VT = V.getSimpleValueType();
18794     SmallVector<SDValue, 32> Masks(
18795         VT.getVectorNumElements(),
18796         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18797     return DAG.getNode(ISD::AND, DL, VT, V,
18798                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18799   };
18800
18801   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18802   // x86, so set the SRL type to have elements at least i16 wide. This is
18803   // correct because all of our SRLs are followed immediately by a mask anyways
18804   // that handles any bits that sneak into the high bits of the byte elements.
18805   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18806
18807   SDValue V = Op;
18808
18809   // v = v - ((v >> 1) & 0x55555555...)
18810   SDValue Srl =
18811       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18812   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18813   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18814
18815   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18816   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18817   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18818   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18819   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18820
18821   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18822   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18823   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18824   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18825
18826   // At this point, V contains the byte-wise population count, and we are
18827   // merely doing a horizontal sum if necessary to get the wider element
18828   // counts.
18829   if (EltVT == MVT::i8)
18830     return V;
18831
18832   return LowerHorizontalByteSum(
18833       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18834       DAG);
18835 }
18836
18837 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18838                                 SelectionDAG &DAG) {
18839   MVT VT = Op.getSimpleValueType();
18840   // FIXME: Need to add AVX-512 support here!
18841   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18842          "Unknown CTPOP type to handle");
18843   SDLoc DL(Op.getNode());
18844   SDValue Op0 = Op.getOperand(0);
18845
18846   if (!Subtarget->hasSSSE3()) {
18847     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18848     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18849     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18850   }
18851
18852   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18853     unsigned NumElems = VT.getVectorNumElements();
18854
18855     // Extract each 128-bit vector, compute pop count and concat the result.
18856     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18857     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18858
18859     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18860                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18861                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18862   }
18863
18864   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18865 }
18866
18867 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18868                           SelectionDAG &DAG) {
18869   assert(Op.getValueType().isVector() &&
18870          "We only do custom lowering for vector population count.");
18871   return LowerVectorCTPOP(Op, Subtarget, DAG);
18872 }
18873
18874 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18875   SDNode *Node = Op.getNode();
18876   SDLoc dl(Node);
18877   EVT T = Node->getValueType(0);
18878   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18879                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18880   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18881                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18882                        Node->getOperand(0),
18883                        Node->getOperand(1), negOp,
18884                        cast<AtomicSDNode>(Node)->getMemOperand(),
18885                        cast<AtomicSDNode>(Node)->getOrdering(),
18886                        cast<AtomicSDNode>(Node)->getSynchScope());
18887 }
18888
18889 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18890   SDNode *Node = Op.getNode();
18891   SDLoc dl(Node);
18892   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18893
18894   // Convert seq_cst store -> xchg
18895   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18896   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18897   //        (The only way to get a 16-byte store is cmpxchg16b)
18898   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18899   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18900       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18901     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18902                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18903                                  Node->getOperand(0),
18904                                  Node->getOperand(1), Node->getOperand(2),
18905                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18906                                  cast<AtomicSDNode>(Node)->getOrdering(),
18907                                  cast<AtomicSDNode>(Node)->getSynchScope());
18908     return Swap.getValue(1);
18909   }
18910   // Other atomic stores have a simple pattern.
18911   return Op;
18912 }
18913
18914 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18915   EVT VT = Op.getNode()->getSimpleValueType(0);
18916
18917   // Let legalize expand this if it isn't a legal type yet.
18918   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18919     return SDValue();
18920
18921   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18922
18923   unsigned Opc;
18924   bool ExtraOp = false;
18925   switch (Op.getOpcode()) {
18926   default: llvm_unreachable("Invalid code");
18927   case ISD::ADDC: Opc = X86ISD::ADD; break;
18928   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18929   case ISD::SUBC: Opc = X86ISD::SUB; break;
18930   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18931   }
18932
18933   if (!ExtraOp)
18934     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18935                        Op.getOperand(1));
18936   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18937                      Op.getOperand(1), Op.getOperand(2));
18938 }
18939
18940 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18941                             SelectionDAG &DAG) {
18942   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18943
18944   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18945   // which returns the values as { float, float } (in XMM0) or
18946   // { double, double } (which is returned in XMM0, XMM1).
18947   SDLoc dl(Op);
18948   SDValue Arg = Op.getOperand(0);
18949   EVT ArgVT = Arg.getValueType();
18950   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18951
18952   TargetLowering::ArgListTy Args;
18953   TargetLowering::ArgListEntry Entry;
18954
18955   Entry.Node = Arg;
18956   Entry.Ty = ArgTy;
18957   Entry.isSExt = false;
18958   Entry.isZExt = false;
18959   Args.push_back(Entry);
18960
18961   bool isF64 = ArgVT == MVT::f64;
18962   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18963   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18964   // the results are returned via SRet in memory.
18965   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18966   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18967   SDValue Callee =
18968       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18969
18970   Type *RetTy = isF64
18971     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18972     : (Type*)VectorType::get(ArgTy, 4);
18973
18974   TargetLowering::CallLoweringInfo CLI(DAG);
18975   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18976     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18977
18978   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18979
18980   if (isF64)
18981     // Returned in xmm0 and xmm1.
18982     return CallResult.first;
18983
18984   // Returned in bits 0:31 and 32:64 xmm0.
18985   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18986                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18987   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18988                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18989   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18990   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18991 }
18992
18993 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18994                              SelectionDAG &DAG) {
18995   assert(Subtarget->hasAVX512() &&
18996          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18997
18998   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18999   EVT VT = N->getValue().getValueType();
19000   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19001   SDLoc dl(Op);
19002
19003   // X86 scatter kills mask register, so its type should be added to
19004   // the list of return values
19005   if (N->getNumValues() == 1) {
19006     SDValue Index = N->getIndex();
19007     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19008         !Index.getValueType().is512BitVector())
19009       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19010
19011     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19012     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19013                       N->getOperand(3), Index };
19014
19015     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19016     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19017     return SDValue(NewScatter.getNode(), 0);
19018   }
19019   return Op;
19020 }
19021
19022 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19023                             SelectionDAG &DAG) {
19024   assert(Subtarget->hasAVX512() &&
19025          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19026
19027   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19028   EVT VT = Op.getValueType();
19029   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19030   SDLoc dl(Op);
19031
19032   SDValue Index = N->getIndex();
19033   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19034       !Index.getValueType().is512BitVector()) {
19035     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19036     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19037                       N->getOperand(3), Index };
19038     DAG.UpdateNodeOperands(N, Ops);
19039   }
19040   return Op;
19041 }
19042
19043 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19044                                                     SelectionDAG &DAG) const {
19045   // TODO: Eventually, the lowering of these nodes should be informed by or
19046   // deferred to the GC strategy for the function in which they appear. For
19047   // now, however, they must be lowered to something. Since they are logically
19048   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19049   // require special handling for these nodes), lower them as literal NOOPs for
19050   // the time being.
19051   SmallVector<SDValue, 2> Ops;
19052
19053   Ops.push_back(Op.getOperand(0));
19054   if (Op->getGluedNode())
19055     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19056
19057   SDLoc OpDL(Op);
19058   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19059   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19060
19061   return NOOP;
19062 }
19063
19064 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19065                                                   SelectionDAG &DAG) const {
19066   // TODO: Eventually, the lowering of these nodes should be informed by or
19067   // deferred to the GC strategy for the function in which they appear. For
19068   // now, however, they must be lowered to something. Since they are logically
19069   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19070   // require special handling for these nodes), lower them as literal NOOPs for
19071   // the time being.
19072   SmallVector<SDValue, 2> Ops;
19073
19074   Ops.push_back(Op.getOperand(0));
19075   if (Op->getGluedNode())
19076     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19077
19078   SDLoc OpDL(Op);
19079   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19080   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19081
19082   return NOOP;
19083 }
19084
19085 /// LowerOperation - Provide custom lowering hooks for some operations.
19086 ///
19087 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19088   switch (Op.getOpcode()) {
19089   default: llvm_unreachable("Should not custom lower this!");
19090   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19091   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19092     return LowerCMP_SWAP(Op, Subtarget, DAG);
19093   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19094   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19095   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19096   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19097   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19098   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19099   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19100   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19101   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19102   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19103   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19104   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19105   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19106   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19107   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19108   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19109   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19110   case ISD::SHL_PARTS:
19111   case ISD::SRA_PARTS:
19112   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19113   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19114   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19115   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19116   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19117   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19118   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19119   case ISD::SIGN_EXTEND_VECTOR_INREG:
19120     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19121   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19122   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19123   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19124   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19125   case ISD::FABS:
19126   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19127   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19128   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19129   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19130   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19131   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19132   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19133   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19134   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19135   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19136   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19137   case ISD::INTRINSIC_VOID:
19138   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19139   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19140   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19141   case ISD::FRAME_TO_ARGS_OFFSET:
19142                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19143   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19144   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19145   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
19146   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19147   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19148   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19149   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19150   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19151   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19152   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19153   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19154   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19155   case ISD::UMUL_LOHI:
19156   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19157   case ISD::SRA:
19158   case ISD::SRL:
19159   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19160   case ISD::SADDO:
19161   case ISD::UADDO:
19162   case ISD::SSUBO:
19163   case ISD::USUBO:
19164   case ISD::SMULO:
19165   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19166   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19167   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19168   case ISD::ADDC:
19169   case ISD::ADDE:
19170   case ISD::SUBC:
19171   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19172   case ISD::ADD:                return LowerADD(Op, DAG);
19173   case ISD::SUB:                return LowerSUB(Op, DAG);
19174   case ISD::SMAX:
19175   case ISD::SMIN:
19176   case ISD::UMAX:
19177   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19178   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19179   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19180   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19181   case ISD::GC_TRANSITION_START:
19182                                 return LowerGC_TRANSITION_START(Op, DAG);
19183   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19184   }
19185 }
19186
19187 /// ReplaceNodeResults - Replace a node with an illegal result type
19188 /// with a new node built out of custom code.
19189 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19190                                            SmallVectorImpl<SDValue>&Results,
19191                                            SelectionDAG &DAG) const {
19192   SDLoc dl(N);
19193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19194   switch (N->getOpcode()) {
19195   default:
19196     llvm_unreachable("Do not know how to custom type legalize this operation!");
19197   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19198   case X86ISD::FMINC:
19199   case X86ISD::FMIN:
19200   case X86ISD::FMAXC:
19201   case X86ISD::FMAX: {
19202     EVT VT = N->getValueType(0);
19203     if (VT != MVT::v2f32)
19204       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19205     SDValue UNDEF = DAG.getUNDEF(VT);
19206     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19207                               N->getOperand(0), UNDEF);
19208     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19209                               N->getOperand(1), UNDEF);
19210     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19211     return;
19212   }
19213   case ISD::SIGN_EXTEND_INREG:
19214   case ISD::ADDC:
19215   case ISD::ADDE:
19216   case ISD::SUBC:
19217   case ISD::SUBE:
19218     // We don't want to expand or promote these.
19219     return;
19220   case ISD::SDIV:
19221   case ISD::UDIV:
19222   case ISD::SREM:
19223   case ISD::UREM:
19224   case ISD::SDIVREM:
19225   case ISD::UDIVREM: {
19226     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19227     Results.push_back(V);
19228     return;
19229   }
19230   case ISD::FP_TO_SINT:
19231   case ISD::FP_TO_UINT: {
19232     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19233
19234     std::pair<SDValue,SDValue> Vals =
19235         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19236     SDValue FIST = Vals.first, StackSlot = Vals.second;
19237     if (FIST.getNode()) {
19238       EVT VT = N->getValueType(0);
19239       // Return a load from the stack slot.
19240       if (StackSlot.getNode())
19241         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19242                                       MachinePointerInfo(),
19243                                       false, false, false, 0));
19244       else
19245         Results.push_back(FIST);
19246     }
19247     return;
19248   }
19249   case ISD::UINT_TO_FP: {
19250     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19251     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19252         N->getValueType(0) != MVT::v2f32)
19253       return;
19254     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19255                                  N->getOperand(0));
19256     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19257                                      MVT::f64);
19258     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19259     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19260                              DAG.getBitcast(MVT::v2i64, VBias));
19261     Or = DAG.getBitcast(MVT::v2f64, Or);
19262     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19263     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19264     return;
19265   }
19266   case ISD::FP_ROUND: {
19267     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19268         return;
19269     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19270     Results.push_back(V);
19271     return;
19272   }
19273   case ISD::FP_EXTEND: {
19274     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19275     // No other ValueType for FP_EXTEND should reach this point.
19276     assert(N->getValueType(0) == MVT::v2f32 &&
19277            "Do not know how to legalize this Node");
19278     return;
19279   }
19280   case ISD::INTRINSIC_W_CHAIN: {
19281     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19282     switch (IntNo) {
19283     default : llvm_unreachable("Do not know how to custom type "
19284                                "legalize this intrinsic operation!");
19285     case Intrinsic::x86_rdtsc:
19286       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19287                                      Results);
19288     case Intrinsic::x86_rdtscp:
19289       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19290                                      Results);
19291     case Intrinsic::x86_rdpmc:
19292       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19293     }
19294   }
19295   case ISD::READCYCLECOUNTER: {
19296     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19297                                    Results);
19298   }
19299   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19300     EVT T = N->getValueType(0);
19301     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19302     bool Regs64bit = T == MVT::i128;
19303     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19304     SDValue cpInL, cpInH;
19305     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19306                         DAG.getConstant(0, dl, HalfT));
19307     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19308                         DAG.getConstant(1, dl, HalfT));
19309     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19310                              Regs64bit ? X86::RAX : X86::EAX,
19311                              cpInL, SDValue());
19312     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19313                              Regs64bit ? X86::RDX : X86::EDX,
19314                              cpInH, cpInL.getValue(1));
19315     SDValue swapInL, swapInH;
19316     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19317                           DAG.getConstant(0, dl, HalfT));
19318     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19319                           DAG.getConstant(1, dl, HalfT));
19320     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19321                                Regs64bit ? X86::RBX : X86::EBX,
19322                                swapInL, cpInH.getValue(1));
19323     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19324                                Regs64bit ? X86::RCX : X86::ECX,
19325                                swapInH, swapInL.getValue(1));
19326     SDValue Ops[] = { swapInH.getValue(0),
19327                       N->getOperand(1),
19328                       swapInH.getValue(1) };
19329     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19330     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19331     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19332                                   X86ISD::LCMPXCHG8_DAG;
19333     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19334     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19335                                         Regs64bit ? X86::RAX : X86::EAX,
19336                                         HalfT, Result.getValue(1));
19337     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19338                                         Regs64bit ? X86::RDX : X86::EDX,
19339                                         HalfT, cpOutL.getValue(2));
19340     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19341
19342     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19343                                         MVT::i32, cpOutH.getValue(2));
19344     SDValue Success =
19345         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19346                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19347     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19348
19349     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19350     Results.push_back(Success);
19351     Results.push_back(EFLAGS.getValue(1));
19352     return;
19353   }
19354   case ISD::ATOMIC_SWAP:
19355   case ISD::ATOMIC_LOAD_ADD:
19356   case ISD::ATOMIC_LOAD_SUB:
19357   case ISD::ATOMIC_LOAD_AND:
19358   case ISD::ATOMIC_LOAD_OR:
19359   case ISD::ATOMIC_LOAD_XOR:
19360   case ISD::ATOMIC_LOAD_NAND:
19361   case ISD::ATOMIC_LOAD_MIN:
19362   case ISD::ATOMIC_LOAD_MAX:
19363   case ISD::ATOMIC_LOAD_UMIN:
19364   case ISD::ATOMIC_LOAD_UMAX:
19365   case ISD::ATOMIC_LOAD: {
19366     // Delegate to generic TypeLegalization. Situations we can really handle
19367     // should have already been dealt with by AtomicExpandPass.cpp.
19368     break;
19369   }
19370   case ISD::BITCAST: {
19371     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19372     EVT DstVT = N->getValueType(0);
19373     EVT SrcVT = N->getOperand(0)->getValueType(0);
19374
19375     if (SrcVT != MVT::f64 ||
19376         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19377       return;
19378
19379     unsigned NumElts = DstVT.getVectorNumElements();
19380     EVT SVT = DstVT.getVectorElementType();
19381     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19382     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19383                                    MVT::v2f64, N->getOperand(0));
19384     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19385
19386     if (ExperimentalVectorWideningLegalization) {
19387       // If we are legalizing vectors by widening, we already have the desired
19388       // legal vector type, just return it.
19389       Results.push_back(ToVecInt);
19390       return;
19391     }
19392
19393     SmallVector<SDValue, 8> Elts;
19394     for (unsigned i = 0, e = NumElts; i != e; ++i)
19395       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19396                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19397
19398     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19399   }
19400   }
19401 }
19402
19403 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19404   switch ((X86ISD::NodeType)Opcode) {
19405   case X86ISD::FIRST_NUMBER:       break;
19406   case X86ISD::BSF:                return "X86ISD::BSF";
19407   case X86ISD::BSR:                return "X86ISD::BSR";
19408   case X86ISD::SHLD:               return "X86ISD::SHLD";
19409   case X86ISD::SHRD:               return "X86ISD::SHRD";
19410   case X86ISD::FAND:               return "X86ISD::FAND";
19411   case X86ISD::FANDN:              return "X86ISD::FANDN";
19412   case X86ISD::FOR:                return "X86ISD::FOR";
19413   case X86ISD::FXOR:               return "X86ISD::FXOR";
19414   case X86ISD::FILD:               return "X86ISD::FILD";
19415   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19416   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19417   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19418   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19419   case X86ISD::FLD:                return "X86ISD::FLD";
19420   case X86ISD::FST:                return "X86ISD::FST";
19421   case X86ISD::CALL:               return "X86ISD::CALL";
19422   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19423   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19424   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19425   case X86ISD::BT:                 return "X86ISD::BT";
19426   case X86ISD::CMP:                return "X86ISD::CMP";
19427   case X86ISD::COMI:               return "X86ISD::COMI";
19428   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19429   case X86ISD::CMPM:               return "X86ISD::CMPM";
19430   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19431   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19432   case X86ISD::SETCC:              return "X86ISD::SETCC";
19433   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19434   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19435   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19436   case X86ISD::CMOV:               return "X86ISD::CMOV";
19437   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19438   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19439   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19440   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19441   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19442   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19443   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19444   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19445   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19446   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19447   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19448   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19449   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19450   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19451   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19452   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19453   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19454   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19455   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19456   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19457   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19458   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19459   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19460   case X86ISD::HADD:               return "X86ISD::HADD";
19461   case X86ISD::HSUB:               return "X86ISD::HSUB";
19462   case X86ISD::FHADD:              return "X86ISD::FHADD";
19463   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19464   case X86ISD::ABS:                return "X86ISD::ABS";
19465   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19466   case X86ISD::FMAX:               return "X86ISD::FMAX";
19467   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19468   case X86ISD::FMIN:               return "X86ISD::FMIN";
19469   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19470   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19471   case X86ISD::FMINC:              return "X86ISD::FMINC";
19472   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19473   case X86ISD::FRCP:               return "X86ISD::FRCP";
19474   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19475   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19476   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19477   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19478   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19479   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19480   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19481   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19482   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19483   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19484   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19485   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19486   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19487   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19488   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19489   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19490   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19491   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19492   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19493   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19494   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19495   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19496   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19497   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19498   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19499   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19500   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19501   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19502   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19503   case X86ISD::VSHL:               return "X86ISD::VSHL";
19504   case X86ISD::VSRL:               return "X86ISD::VSRL";
19505   case X86ISD::VSRA:               return "X86ISD::VSRA";
19506   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19507   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19508   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19509   case X86ISD::CMPP:               return "X86ISD::CMPP";
19510   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19511   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19512   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19513   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19514   case X86ISD::ADD:                return "X86ISD::ADD";
19515   case X86ISD::SUB:                return "X86ISD::SUB";
19516   case X86ISD::ADC:                return "X86ISD::ADC";
19517   case X86ISD::SBB:                return "X86ISD::SBB";
19518   case X86ISD::SMUL:               return "X86ISD::SMUL";
19519   case X86ISD::UMUL:               return "X86ISD::UMUL";
19520   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19521   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19522   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19523   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19524   case X86ISD::INC:                return "X86ISD::INC";
19525   case X86ISD::DEC:                return "X86ISD::DEC";
19526   case X86ISD::OR:                 return "X86ISD::OR";
19527   case X86ISD::XOR:                return "X86ISD::XOR";
19528   case X86ISD::AND:                return "X86ISD::AND";
19529   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19530   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19531   case X86ISD::PTEST:              return "X86ISD::PTEST";
19532   case X86ISD::TESTP:              return "X86ISD::TESTP";
19533   case X86ISD::TESTM:              return "X86ISD::TESTM";
19534   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19535   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19536   case X86ISD::KTEST:              return "X86ISD::KTEST";
19537   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19538   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19539   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19540   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19541   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19542   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19543   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19544   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19545   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19546   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19547   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19548   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19549   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19550   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19551   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19552   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19553   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19554   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19555   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19556   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19557   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19558   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19559   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19560   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19561   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19562   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19563   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19564   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19565   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19566   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19567   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19568   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19569   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19570   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19571   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19572   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19573   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19574   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19575   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19576   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19577   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19578   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19579   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19580   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19581   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19582   case X86ISD::SAHF:               return "X86ISD::SAHF";
19583   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19584   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19585   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19586   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19587   case X86ISD::FMADD:              return "X86ISD::FMADD";
19588   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19589   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19590   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19591   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19592   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19593   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19594   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19595   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19596   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19597   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19598   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19599   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19600   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19601   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19602   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19603   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19604   case X86ISD::XTEST:              return "X86ISD::XTEST";
19605   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19606   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19607   case X86ISD::SELECT:             return "X86ISD::SELECT";
19608   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19609   case X86ISD::RCP28:              return "X86ISD::RCP28";
19610   case X86ISD::EXP2:               return "X86ISD::EXP2";
19611   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19612   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19613   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19614   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19615   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19616   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19617   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19618   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19619   case X86ISD::ADDS:               return "X86ISD::ADDS";
19620   case X86ISD::SUBS:               return "X86ISD::SUBS";
19621   case X86ISD::AVG:                return "X86ISD::AVG";
19622   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19623   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19624   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19625   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19626   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19627   }
19628   return nullptr;
19629 }
19630
19631 // isLegalAddressingMode - Return true if the addressing mode represented
19632 // by AM is legal for this target, for a load/store of the specified type.
19633 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19634                                               const AddrMode &AM, Type *Ty,
19635                                               unsigned AS) const {
19636   // X86 supports extremely general addressing modes.
19637   CodeModel::Model M = getTargetMachine().getCodeModel();
19638   Reloc::Model R = getTargetMachine().getRelocationModel();
19639
19640   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19641   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19642     return false;
19643
19644   if (AM.BaseGV) {
19645     unsigned GVFlags =
19646       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19647
19648     // If a reference to this global requires an extra load, we can't fold it.
19649     if (isGlobalStubReference(GVFlags))
19650       return false;
19651
19652     // If BaseGV requires a register for the PIC base, we cannot also have a
19653     // BaseReg specified.
19654     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19655       return false;
19656
19657     // If lower 4G is not available, then we must use rip-relative addressing.
19658     if ((M != CodeModel::Small || R != Reloc::Static) &&
19659         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19660       return false;
19661   }
19662
19663   switch (AM.Scale) {
19664   case 0:
19665   case 1:
19666   case 2:
19667   case 4:
19668   case 8:
19669     // These scales always work.
19670     break;
19671   case 3:
19672   case 5:
19673   case 9:
19674     // These scales are formed with basereg+scalereg.  Only accept if there is
19675     // no basereg yet.
19676     if (AM.HasBaseReg)
19677       return false;
19678     break;
19679   default:  // Other stuff never works.
19680     return false;
19681   }
19682
19683   return true;
19684 }
19685
19686 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19687   unsigned Bits = Ty->getScalarSizeInBits();
19688
19689   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19690   // particularly cheaper than those without.
19691   if (Bits == 8)
19692     return false;
19693
19694   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19695   // variable shifts just as cheap as scalar ones.
19696   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19697     return false;
19698
19699   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19700   // fully general vector.
19701   return true;
19702 }
19703
19704 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19705   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19706     return false;
19707   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19708   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19709   return NumBits1 > NumBits2;
19710 }
19711
19712 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19713   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19714     return false;
19715
19716   if (!isTypeLegal(EVT::getEVT(Ty1)))
19717     return false;
19718
19719   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19720
19721   // Assuming the caller doesn't have a zeroext or signext return parameter,
19722   // truncation all the way down to i1 is valid.
19723   return true;
19724 }
19725
19726 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19727   return isInt<32>(Imm);
19728 }
19729
19730 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19731   // Can also use sub to handle negated immediates.
19732   return isInt<32>(Imm);
19733 }
19734
19735 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19736   if (!VT1.isInteger() || !VT2.isInteger())
19737     return false;
19738   unsigned NumBits1 = VT1.getSizeInBits();
19739   unsigned NumBits2 = VT2.getSizeInBits();
19740   return NumBits1 > NumBits2;
19741 }
19742
19743 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19744   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19745   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19746 }
19747
19748 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19749   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19750   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19751 }
19752
19753 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19754   EVT VT1 = Val.getValueType();
19755   if (isZExtFree(VT1, VT2))
19756     return true;
19757
19758   if (Val.getOpcode() != ISD::LOAD)
19759     return false;
19760
19761   if (!VT1.isSimple() || !VT1.isInteger() ||
19762       !VT2.isSimple() || !VT2.isInteger())
19763     return false;
19764
19765   switch (VT1.getSimpleVT().SimpleTy) {
19766   default: break;
19767   case MVT::i8:
19768   case MVT::i16:
19769   case MVT::i32:
19770     // X86 has 8, 16, and 32-bit zero-extending loads.
19771     return true;
19772   }
19773
19774   return false;
19775 }
19776
19777 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19778
19779 bool
19780 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19781   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19782     return false;
19783
19784   VT = VT.getScalarType();
19785
19786   if (!VT.isSimple())
19787     return false;
19788
19789   switch (VT.getSimpleVT().SimpleTy) {
19790   case MVT::f32:
19791   case MVT::f64:
19792     return true;
19793   default:
19794     break;
19795   }
19796
19797   return false;
19798 }
19799
19800 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19801   // i16 instructions are longer (0x66 prefix) and potentially slower.
19802   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19803 }
19804
19805 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19806 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19807 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19808 /// are assumed to be legal.
19809 bool
19810 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19811                                       EVT VT) const {
19812   if (!VT.isSimple())
19813     return false;
19814
19815   // Not for i1 vectors
19816   if (VT.getScalarType() == MVT::i1)
19817     return false;
19818
19819   // Very little shuffling can be done for 64-bit vectors right now.
19820   if (VT.getSizeInBits() == 64)
19821     return false;
19822
19823   // We only care that the types being shuffled are legal. The lowering can
19824   // handle any possible shuffle mask that results.
19825   return isTypeLegal(VT.getSimpleVT());
19826 }
19827
19828 bool
19829 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19830                                           EVT VT) const {
19831   // Just delegate to the generic legality, clear masks aren't special.
19832   return isShuffleMaskLegal(Mask, VT);
19833 }
19834
19835 //===----------------------------------------------------------------------===//
19836 //                           X86 Scheduler Hooks
19837 //===----------------------------------------------------------------------===//
19838
19839 /// Utility function to emit xbegin specifying the start of an RTM region.
19840 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19841                                      const TargetInstrInfo *TII) {
19842   DebugLoc DL = MI->getDebugLoc();
19843
19844   const BasicBlock *BB = MBB->getBasicBlock();
19845   MachineFunction::iterator I = MBB;
19846   ++I;
19847
19848   // For the v = xbegin(), we generate
19849   //
19850   // thisMBB:
19851   //  xbegin sinkMBB
19852   //
19853   // mainMBB:
19854   //  eax = -1
19855   //
19856   // sinkMBB:
19857   //  v = eax
19858
19859   MachineBasicBlock *thisMBB = MBB;
19860   MachineFunction *MF = MBB->getParent();
19861   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19862   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19863   MF->insert(I, mainMBB);
19864   MF->insert(I, sinkMBB);
19865
19866   // Transfer the remainder of BB and its successor edges to sinkMBB.
19867   sinkMBB->splice(sinkMBB->begin(), MBB,
19868                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19869   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19870
19871   // thisMBB:
19872   //  xbegin sinkMBB
19873   //  # fallthrough to mainMBB
19874   //  # abortion to sinkMBB
19875   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19876   thisMBB->addSuccessor(mainMBB);
19877   thisMBB->addSuccessor(sinkMBB);
19878
19879   // mainMBB:
19880   //  EAX = -1
19881   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19882   mainMBB->addSuccessor(sinkMBB);
19883
19884   // sinkMBB:
19885   // EAX is live into the sinkMBB
19886   sinkMBB->addLiveIn(X86::EAX);
19887   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19888           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19889     .addReg(X86::EAX);
19890
19891   MI->eraseFromParent();
19892   return sinkMBB;
19893 }
19894
19895 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19896 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19897 // in the .td file.
19898 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19899                                        const TargetInstrInfo *TII) {
19900   unsigned Opc;
19901   switch (MI->getOpcode()) {
19902   default: llvm_unreachable("illegal opcode!");
19903   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19904   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19905   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19906   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19907   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19908   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19909   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19910   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19911   }
19912
19913   DebugLoc dl = MI->getDebugLoc();
19914   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19915
19916   unsigned NumArgs = MI->getNumOperands();
19917   for (unsigned i = 1; i < NumArgs; ++i) {
19918     MachineOperand &Op = MI->getOperand(i);
19919     if (!(Op.isReg() && Op.isImplicit()))
19920       MIB.addOperand(Op);
19921   }
19922   if (MI->hasOneMemOperand())
19923     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19924
19925   BuildMI(*BB, MI, dl,
19926     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19927     .addReg(X86::XMM0);
19928
19929   MI->eraseFromParent();
19930   return BB;
19931 }
19932
19933 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19934 // defs in an instruction pattern
19935 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19936                                        const TargetInstrInfo *TII) {
19937   unsigned Opc;
19938   switch (MI->getOpcode()) {
19939   default: llvm_unreachable("illegal opcode!");
19940   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19941   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19942   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19943   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19944   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19945   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19946   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19947   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19948   }
19949
19950   DebugLoc dl = MI->getDebugLoc();
19951   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19952
19953   unsigned NumArgs = MI->getNumOperands(); // remove the results
19954   for (unsigned i = 1; i < NumArgs; ++i) {
19955     MachineOperand &Op = MI->getOperand(i);
19956     if (!(Op.isReg() && Op.isImplicit()))
19957       MIB.addOperand(Op);
19958   }
19959   if (MI->hasOneMemOperand())
19960     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19961
19962   BuildMI(*BB, MI, dl,
19963     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19964     .addReg(X86::ECX);
19965
19966   MI->eraseFromParent();
19967   return BB;
19968 }
19969
19970 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19971                                       const X86Subtarget *Subtarget) {
19972   DebugLoc dl = MI->getDebugLoc();
19973   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19974   // Address into RAX/EAX, other two args into ECX, EDX.
19975   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19976   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19977   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19978   for (int i = 0; i < X86::AddrNumOperands; ++i)
19979     MIB.addOperand(MI->getOperand(i));
19980
19981   unsigned ValOps = X86::AddrNumOperands;
19982   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19983     .addReg(MI->getOperand(ValOps).getReg());
19984   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19985     .addReg(MI->getOperand(ValOps+1).getReg());
19986
19987   // The instruction doesn't actually take any operands though.
19988   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19989
19990   MI->eraseFromParent(); // The pseudo is gone now.
19991   return BB;
19992 }
19993
19994 MachineBasicBlock *
19995 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19996                                                  MachineBasicBlock *MBB) const {
19997   // Emit va_arg instruction on X86-64.
19998
19999   // Operands to this pseudo-instruction:
20000   // 0  ) Output        : destination address (reg)
20001   // 1-5) Input         : va_list address (addr, i64mem)
20002   // 6  ) ArgSize       : Size (in bytes) of vararg type
20003   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20004   // 8  ) Align         : Alignment of type
20005   // 9  ) EFLAGS (implicit-def)
20006
20007   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20008   static_assert(X86::AddrNumOperands == 5,
20009                 "VAARG_64 assumes 5 address operands");
20010
20011   unsigned DestReg = MI->getOperand(0).getReg();
20012   MachineOperand &Base = MI->getOperand(1);
20013   MachineOperand &Scale = MI->getOperand(2);
20014   MachineOperand &Index = MI->getOperand(3);
20015   MachineOperand &Disp = MI->getOperand(4);
20016   MachineOperand &Segment = MI->getOperand(5);
20017   unsigned ArgSize = MI->getOperand(6).getImm();
20018   unsigned ArgMode = MI->getOperand(7).getImm();
20019   unsigned Align = MI->getOperand(8).getImm();
20020
20021   // Memory Reference
20022   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20023   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20024   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20025
20026   // Machine Information
20027   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20028   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20029   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20030   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20031   DebugLoc DL = MI->getDebugLoc();
20032
20033   // struct va_list {
20034   //   i32   gp_offset
20035   //   i32   fp_offset
20036   //   i64   overflow_area (address)
20037   //   i64   reg_save_area (address)
20038   // }
20039   // sizeof(va_list) = 24
20040   // alignment(va_list) = 8
20041
20042   unsigned TotalNumIntRegs = 6;
20043   unsigned TotalNumXMMRegs = 8;
20044   bool UseGPOffset = (ArgMode == 1);
20045   bool UseFPOffset = (ArgMode == 2);
20046   unsigned MaxOffset = TotalNumIntRegs * 8 +
20047                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20048
20049   /* Align ArgSize to a multiple of 8 */
20050   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20051   bool NeedsAlign = (Align > 8);
20052
20053   MachineBasicBlock *thisMBB = MBB;
20054   MachineBasicBlock *overflowMBB;
20055   MachineBasicBlock *offsetMBB;
20056   MachineBasicBlock *endMBB;
20057
20058   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20059   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20060   unsigned OffsetReg = 0;
20061
20062   if (!UseGPOffset && !UseFPOffset) {
20063     // If we only pull from the overflow region, we don't create a branch.
20064     // We don't need to alter control flow.
20065     OffsetDestReg = 0; // unused
20066     OverflowDestReg = DestReg;
20067
20068     offsetMBB = nullptr;
20069     overflowMBB = thisMBB;
20070     endMBB = thisMBB;
20071   } else {
20072     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20073     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20074     // If not, pull from overflow_area. (branch to overflowMBB)
20075     //
20076     //       thisMBB
20077     //         |     .
20078     //         |        .
20079     //     offsetMBB   overflowMBB
20080     //         |        .
20081     //         |     .
20082     //        endMBB
20083
20084     // Registers for the PHI in endMBB
20085     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20086     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20087
20088     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20089     MachineFunction *MF = MBB->getParent();
20090     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20091     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20092     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20093
20094     MachineFunction::iterator MBBIter = MBB;
20095     ++MBBIter;
20096
20097     // Insert the new basic blocks
20098     MF->insert(MBBIter, offsetMBB);
20099     MF->insert(MBBIter, overflowMBB);
20100     MF->insert(MBBIter, endMBB);
20101
20102     // Transfer the remainder of MBB and its successor edges to endMBB.
20103     endMBB->splice(endMBB->begin(), thisMBB,
20104                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20105     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20106
20107     // Make offsetMBB and overflowMBB successors of thisMBB
20108     thisMBB->addSuccessor(offsetMBB);
20109     thisMBB->addSuccessor(overflowMBB);
20110
20111     // endMBB is a successor of both offsetMBB and overflowMBB
20112     offsetMBB->addSuccessor(endMBB);
20113     overflowMBB->addSuccessor(endMBB);
20114
20115     // Load the offset value into a register
20116     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20117     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20118       .addOperand(Base)
20119       .addOperand(Scale)
20120       .addOperand(Index)
20121       .addDisp(Disp, UseFPOffset ? 4 : 0)
20122       .addOperand(Segment)
20123       .setMemRefs(MMOBegin, MMOEnd);
20124
20125     // Check if there is enough room left to pull this argument.
20126     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20127       .addReg(OffsetReg)
20128       .addImm(MaxOffset + 8 - ArgSizeA8);
20129
20130     // Branch to "overflowMBB" if offset >= max
20131     // Fall through to "offsetMBB" otherwise
20132     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20133       .addMBB(overflowMBB);
20134   }
20135
20136   // In offsetMBB, emit code to use the reg_save_area.
20137   if (offsetMBB) {
20138     assert(OffsetReg != 0);
20139
20140     // Read the reg_save_area address.
20141     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20142     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20143       .addOperand(Base)
20144       .addOperand(Scale)
20145       .addOperand(Index)
20146       .addDisp(Disp, 16)
20147       .addOperand(Segment)
20148       .setMemRefs(MMOBegin, MMOEnd);
20149
20150     // Zero-extend the offset
20151     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20152       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20153         .addImm(0)
20154         .addReg(OffsetReg)
20155         .addImm(X86::sub_32bit);
20156
20157     // Add the offset to the reg_save_area to get the final address.
20158     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20159       .addReg(OffsetReg64)
20160       .addReg(RegSaveReg);
20161
20162     // Compute the offset for the next argument
20163     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20164     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20165       .addReg(OffsetReg)
20166       .addImm(UseFPOffset ? 16 : 8);
20167
20168     // Store it back into the va_list.
20169     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20170       .addOperand(Base)
20171       .addOperand(Scale)
20172       .addOperand(Index)
20173       .addDisp(Disp, UseFPOffset ? 4 : 0)
20174       .addOperand(Segment)
20175       .addReg(NextOffsetReg)
20176       .setMemRefs(MMOBegin, MMOEnd);
20177
20178     // Jump to endMBB
20179     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20180       .addMBB(endMBB);
20181   }
20182
20183   //
20184   // Emit code to use overflow area
20185   //
20186
20187   // Load the overflow_area address into a register.
20188   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20189   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20190     .addOperand(Base)
20191     .addOperand(Scale)
20192     .addOperand(Index)
20193     .addDisp(Disp, 8)
20194     .addOperand(Segment)
20195     .setMemRefs(MMOBegin, MMOEnd);
20196
20197   // If we need to align it, do so. Otherwise, just copy the address
20198   // to OverflowDestReg.
20199   if (NeedsAlign) {
20200     // Align the overflow address
20201     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20202     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20203
20204     // aligned_addr = (addr + (align-1)) & ~(align-1)
20205     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20206       .addReg(OverflowAddrReg)
20207       .addImm(Align-1);
20208
20209     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20210       .addReg(TmpReg)
20211       .addImm(~(uint64_t)(Align-1));
20212   } else {
20213     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20214       .addReg(OverflowAddrReg);
20215   }
20216
20217   // Compute the next overflow address after this argument.
20218   // (the overflow address should be kept 8-byte aligned)
20219   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20220   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20221     .addReg(OverflowDestReg)
20222     .addImm(ArgSizeA8);
20223
20224   // Store the new overflow address.
20225   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20226     .addOperand(Base)
20227     .addOperand(Scale)
20228     .addOperand(Index)
20229     .addDisp(Disp, 8)
20230     .addOperand(Segment)
20231     .addReg(NextAddrReg)
20232     .setMemRefs(MMOBegin, MMOEnd);
20233
20234   // If we branched, emit the PHI to the front of endMBB.
20235   if (offsetMBB) {
20236     BuildMI(*endMBB, endMBB->begin(), DL,
20237             TII->get(X86::PHI), DestReg)
20238       .addReg(OffsetDestReg).addMBB(offsetMBB)
20239       .addReg(OverflowDestReg).addMBB(overflowMBB);
20240   }
20241
20242   // Erase the pseudo instruction
20243   MI->eraseFromParent();
20244
20245   return endMBB;
20246 }
20247
20248 MachineBasicBlock *
20249 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20250                                                  MachineInstr *MI,
20251                                                  MachineBasicBlock *MBB) const {
20252   // Emit code to save XMM registers to the stack. The ABI says that the
20253   // number of registers to save is given in %al, so it's theoretically
20254   // possible to do an indirect jump trick to avoid saving all of them,
20255   // however this code takes a simpler approach and just executes all
20256   // of the stores if %al is non-zero. It's less code, and it's probably
20257   // easier on the hardware branch predictor, and stores aren't all that
20258   // expensive anyway.
20259
20260   // Create the new basic blocks. One block contains all the XMM stores,
20261   // and one block is the final destination regardless of whether any
20262   // stores were performed.
20263   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20264   MachineFunction *F = MBB->getParent();
20265   MachineFunction::iterator MBBIter = MBB;
20266   ++MBBIter;
20267   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20268   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20269   F->insert(MBBIter, XMMSaveMBB);
20270   F->insert(MBBIter, EndMBB);
20271
20272   // Transfer the remainder of MBB and its successor edges to EndMBB.
20273   EndMBB->splice(EndMBB->begin(), MBB,
20274                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20275   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20276
20277   // The original block will now fall through to the XMM save block.
20278   MBB->addSuccessor(XMMSaveMBB);
20279   // The XMMSaveMBB will fall through to the end block.
20280   XMMSaveMBB->addSuccessor(EndMBB);
20281
20282   // Now add the instructions.
20283   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20284   DebugLoc DL = MI->getDebugLoc();
20285
20286   unsigned CountReg = MI->getOperand(0).getReg();
20287   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20288   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20289
20290   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20291     // If %al is 0, branch around the XMM save block.
20292     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20293     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20294     MBB->addSuccessor(EndMBB);
20295   }
20296
20297   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20298   // that was just emitted, but clearly shouldn't be "saved".
20299   assert((MI->getNumOperands() <= 3 ||
20300           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20301           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20302          && "Expected last argument to be EFLAGS");
20303   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20304   // In the XMM save block, save all the XMM argument registers.
20305   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20306     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20307     MachineMemOperand *MMO = F->getMachineMemOperand(
20308         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20309         MachineMemOperand::MOStore,
20310         /*Size=*/16, /*Align=*/16);
20311     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20312       .addFrameIndex(RegSaveFrameIndex)
20313       .addImm(/*Scale=*/1)
20314       .addReg(/*IndexReg=*/0)
20315       .addImm(/*Disp=*/Offset)
20316       .addReg(/*Segment=*/0)
20317       .addReg(MI->getOperand(i).getReg())
20318       .addMemOperand(MMO);
20319   }
20320
20321   MI->eraseFromParent();   // The pseudo instruction is gone now.
20322
20323   return EndMBB;
20324 }
20325
20326 // The EFLAGS operand of SelectItr might be missing a kill marker
20327 // because there were multiple uses of EFLAGS, and ISel didn't know
20328 // which to mark. Figure out whether SelectItr should have had a
20329 // kill marker, and set it if it should. Returns the correct kill
20330 // marker value.
20331 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20332                                      MachineBasicBlock* BB,
20333                                      const TargetRegisterInfo* TRI) {
20334   // Scan forward through BB for a use/def of EFLAGS.
20335   MachineBasicBlock::iterator miI(std::next(SelectItr));
20336   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20337     const MachineInstr& mi = *miI;
20338     if (mi.readsRegister(X86::EFLAGS))
20339       return false;
20340     if (mi.definesRegister(X86::EFLAGS))
20341       break; // Should have kill-flag - update below.
20342   }
20343
20344   // If we hit the end of the block, check whether EFLAGS is live into a
20345   // successor.
20346   if (miI == BB->end()) {
20347     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20348                                           sEnd = BB->succ_end();
20349          sItr != sEnd; ++sItr) {
20350       MachineBasicBlock* succ = *sItr;
20351       if (succ->isLiveIn(X86::EFLAGS))
20352         return false;
20353     }
20354   }
20355
20356   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20357   // out. SelectMI should have a kill flag on EFLAGS.
20358   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20359   return true;
20360 }
20361
20362 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20363 // together with other CMOV pseudo-opcodes into a single basic-block with
20364 // conditional jump around it.
20365 static bool isCMOVPseudo(MachineInstr *MI) {
20366   switch (MI->getOpcode()) {
20367   case X86::CMOV_FR32:
20368   case X86::CMOV_FR64:
20369   case X86::CMOV_GR8:
20370   case X86::CMOV_GR16:
20371   case X86::CMOV_GR32:
20372   case X86::CMOV_RFP32:
20373   case X86::CMOV_RFP64:
20374   case X86::CMOV_RFP80:
20375   case X86::CMOV_V2F64:
20376   case X86::CMOV_V2I64:
20377   case X86::CMOV_V4F32:
20378   case X86::CMOV_V4F64:
20379   case X86::CMOV_V4I64:
20380   case X86::CMOV_V16F32:
20381   case X86::CMOV_V8F32:
20382   case X86::CMOV_V8F64:
20383   case X86::CMOV_V8I64:
20384   case X86::CMOV_V8I1:
20385   case X86::CMOV_V16I1:
20386   case X86::CMOV_V32I1:
20387   case X86::CMOV_V64I1:
20388     return true;
20389
20390   default:
20391     return false;
20392   }
20393 }
20394
20395 MachineBasicBlock *
20396 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20397                                      MachineBasicBlock *BB) const {
20398   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20399   DebugLoc DL = MI->getDebugLoc();
20400
20401   // To "insert" a SELECT_CC instruction, we actually have to insert the
20402   // diamond control-flow pattern.  The incoming instruction knows the
20403   // destination vreg to set, the condition code register to branch on, the
20404   // true/false values to select between, and a branch opcode to use.
20405   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20406   MachineFunction::iterator It = BB;
20407   ++It;
20408
20409   //  thisMBB:
20410   //  ...
20411   //   TrueVal = ...
20412   //   cmpTY ccX, r1, r2
20413   //   bCC copy1MBB
20414   //   fallthrough --> copy0MBB
20415   MachineBasicBlock *thisMBB = BB;
20416   MachineFunction *F = BB->getParent();
20417
20418   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20419   // as described above, by inserting a BB, and then making a PHI at the join
20420   // point to select the true and false operands of the CMOV in the PHI.
20421   //
20422   // The code also handles two different cases of multiple CMOV opcodes
20423   // in a row.
20424   //
20425   // Case 1:
20426   // In this case, there are multiple CMOVs in a row, all which are based on
20427   // the same condition setting (or the exact opposite condition setting).
20428   // In this case we can lower all the CMOVs using a single inserted BB, and
20429   // then make a number of PHIs at the join point to model the CMOVs. The only
20430   // trickiness here, is that in a case like:
20431   //
20432   // t2 = CMOV cond1 t1, f1
20433   // t3 = CMOV cond1 t2, f2
20434   //
20435   // when rewriting this into PHIs, we have to perform some renaming on the
20436   // temps since you cannot have a PHI operand refer to a PHI result earlier
20437   // in the same block.  The "simple" but wrong lowering would be:
20438   //
20439   // t2 = PHI t1(BB1), f1(BB2)
20440   // t3 = PHI t2(BB1), f2(BB2)
20441   //
20442   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20443   // renaming is to note that on the path through BB1, t2 is really just a
20444   // copy of t1, and do that renaming, properly generating:
20445   //
20446   // t2 = PHI t1(BB1), f1(BB2)
20447   // t3 = PHI t1(BB1), f2(BB2)
20448   //
20449   // Case 2, we lower cascaded CMOVs such as
20450   //
20451   //   (CMOV (CMOV F, T, cc1), T, cc2)
20452   //
20453   // to two successives branches.  For that, we look for another CMOV as the
20454   // following instruction.
20455   //
20456   // Without this, we would add a PHI between the two jumps, which ends up
20457   // creating a few copies all around. For instance, for
20458   //
20459   //    (sitofp (zext (fcmp une)))
20460   //
20461   // we would generate:
20462   //
20463   //         ucomiss %xmm1, %xmm0
20464   //         movss  <1.0f>, %xmm0
20465   //         movaps  %xmm0, %xmm1
20466   //         jne     .LBB5_2
20467   //         xorps   %xmm1, %xmm1
20468   // .LBB5_2:
20469   //         jp      .LBB5_4
20470   //         movaps  %xmm1, %xmm0
20471   // .LBB5_4:
20472   //         retq
20473   //
20474   // because this custom-inserter would have generated:
20475   //
20476   //   A
20477   //   | \
20478   //   |  B
20479   //   | /
20480   //   C
20481   //   | \
20482   //   |  D
20483   //   | /
20484   //   E
20485   //
20486   // A: X = ...; Y = ...
20487   // B: empty
20488   // C: Z = PHI [X, A], [Y, B]
20489   // D: empty
20490   // E: PHI [X, C], [Z, D]
20491   //
20492   // If we lower both CMOVs in a single step, we can instead generate:
20493   //
20494   //   A
20495   //   | \
20496   //   |  C
20497   //   | /|
20498   //   |/ |
20499   //   |  |
20500   //   |  D
20501   //   | /
20502   //   E
20503   //
20504   // A: X = ...; Y = ...
20505   // D: empty
20506   // E: PHI [X, A], [X, C], [Y, D]
20507   //
20508   // Which, in our sitofp/fcmp example, gives us something like:
20509   //
20510   //         ucomiss %xmm1, %xmm0
20511   //         movss  <1.0f>, %xmm0
20512   //         jne     .LBB5_4
20513   //         jp      .LBB5_4
20514   //         xorps   %xmm0, %xmm0
20515   // .LBB5_4:
20516   //         retq
20517   //
20518   MachineInstr *CascadedCMOV = nullptr;
20519   MachineInstr *LastCMOV = MI;
20520   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20521   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20522   MachineBasicBlock::iterator NextMIIt =
20523       std::next(MachineBasicBlock::iterator(MI));
20524
20525   // Check for case 1, where there are multiple CMOVs with the same condition
20526   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20527   // number of jumps the most.
20528
20529   if (isCMOVPseudo(MI)) {
20530     // See if we have a string of CMOVS with the same condition.
20531     while (NextMIIt != BB->end() &&
20532            isCMOVPseudo(NextMIIt) &&
20533            (NextMIIt->getOperand(3).getImm() == CC ||
20534             NextMIIt->getOperand(3).getImm() == OppCC)) {
20535       LastCMOV = &*NextMIIt;
20536       ++NextMIIt;
20537     }
20538   }
20539
20540   // This checks for case 2, but only do this if we didn't already find
20541   // case 1, as indicated by LastCMOV == MI.
20542   if (LastCMOV == MI &&
20543       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20544       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20545       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20546     CascadedCMOV = &*NextMIIt;
20547   }
20548
20549   MachineBasicBlock *jcc1MBB = nullptr;
20550
20551   // If we have a cascaded CMOV, we lower it to two successive branches to
20552   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20553   if (CascadedCMOV) {
20554     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20555     F->insert(It, jcc1MBB);
20556     jcc1MBB->addLiveIn(X86::EFLAGS);
20557   }
20558
20559   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20560   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20561   F->insert(It, copy0MBB);
20562   F->insert(It, sinkMBB);
20563
20564   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20565   // live into the sink and copy blocks.
20566   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20567
20568   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20569   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20570       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20571     copy0MBB->addLiveIn(X86::EFLAGS);
20572     sinkMBB->addLiveIn(X86::EFLAGS);
20573   }
20574
20575   // Transfer the remainder of BB and its successor edges to sinkMBB.
20576   sinkMBB->splice(sinkMBB->begin(), BB,
20577                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20578   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20579
20580   // Add the true and fallthrough blocks as its successors.
20581   if (CascadedCMOV) {
20582     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20583     BB->addSuccessor(jcc1MBB);
20584
20585     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20586     // jump to the sinkMBB.
20587     jcc1MBB->addSuccessor(copy0MBB);
20588     jcc1MBB->addSuccessor(sinkMBB);
20589   } else {
20590     BB->addSuccessor(copy0MBB);
20591   }
20592
20593   // The true block target of the first (or only) branch is always sinkMBB.
20594   BB->addSuccessor(sinkMBB);
20595
20596   // Create the conditional branch instruction.
20597   unsigned Opc = X86::GetCondBranchFromCond(CC);
20598   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20599
20600   if (CascadedCMOV) {
20601     unsigned Opc2 = X86::GetCondBranchFromCond(
20602         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20603     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20604   }
20605
20606   //  copy0MBB:
20607   //   %FalseValue = ...
20608   //   # fallthrough to sinkMBB
20609   copy0MBB->addSuccessor(sinkMBB);
20610
20611   //  sinkMBB:
20612   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20613   //  ...
20614   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20615   MachineBasicBlock::iterator MIItEnd =
20616     std::next(MachineBasicBlock::iterator(LastCMOV));
20617   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20618   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20619   MachineInstrBuilder MIB;
20620
20621   // As we are creating the PHIs, we have to be careful if there is more than
20622   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20623   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20624   // That also means that PHI construction must work forward from earlier to
20625   // later, and that the code must maintain a mapping from earlier PHI's
20626   // destination registers, and the registers that went into the PHI.
20627
20628   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20629     unsigned DestReg = MIIt->getOperand(0).getReg();
20630     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20631     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20632
20633     // If this CMOV we are generating is the opposite condition from
20634     // the jump we generated, then we have to swap the operands for the
20635     // PHI that is going to be generated.
20636     if (MIIt->getOperand(3).getImm() == OppCC)
20637         std::swap(Op1Reg, Op2Reg);
20638
20639     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20640       Op1Reg = RegRewriteTable[Op1Reg].first;
20641
20642     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20643       Op2Reg = RegRewriteTable[Op2Reg].second;
20644
20645     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20646                   TII->get(X86::PHI), DestReg)
20647           .addReg(Op1Reg).addMBB(copy0MBB)
20648           .addReg(Op2Reg).addMBB(thisMBB);
20649
20650     // Add this PHI to the rewrite table.
20651     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20652   }
20653
20654   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20655   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20656   if (CascadedCMOV) {
20657     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20658     // Copy the PHI result to the register defined by the second CMOV.
20659     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20660             DL, TII->get(TargetOpcode::COPY),
20661             CascadedCMOV->getOperand(0).getReg())
20662         .addReg(MI->getOperand(0).getReg());
20663     CascadedCMOV->eraseFromParent();
20664   }
20665
20666   // Now remove the CMOV(s).
20667   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20668     (MIIt++)->eraseFromParent();
20669
20670   return sinkMBB;
20671 }
20672
20673 MachineBasicBlock *
20674 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20675                                        MachineBasicBlock *BB) const {
20676   // Combine the following atomic floating-point modification pattern:
20677   //   a.store(reg OP a.load(acquire), release)
20678   // Transform them into:
20679   //   OPss (%gpr), %xmm
20680   //   movss %xmm, (%gpr)
20681   // Or sd equivalent for 64-bit operations.
20682   unsigned MOp, FOp;
20683   switch (MI->getOpcode()) {
20684   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20685   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20686   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20687   }
20688   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20689   DebugLoc DL = MI->getDebugLoc();
20690   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20691   unsigned MSrc = MI->getOperand(0).getReg();
20692   unsigned VSrc = MI->getOperand(5).getReg();
20693   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20694                                 .addReg(/*Base=*/MSrc)
20695                                 .addImm(/*Scale=*/1)
20696                                 .addReg(/*Index=*/0)
20697                                 .addImm(0)
20698                                 .addReg(0);
20699   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20700                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20701                           .addReg(VSrc)
20702                           .addReg(/*Base=*/MSrc)
20703                           .addImm(/*Scale=*/1)
20704                           .addReg(/*Index=*/0)
20705                           .addImm(/*Disp=*/0)
20706                           .addReg(/*Segment=*/0);
20707   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20708   MI->eraseFromParent(); // The pseudo instruction is gone now.
20709   return BB;
20710 }
20711
20712 MachineBasicBlock *
20713 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20714                                         MachineBasicBlock *BB) const {
20715   MachineFunction *MF = BB->getParent();
20716   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20717   DebugLoc DL = MI->getDebugLoc();
20718   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20719
20720   assert(MF->shouldSplitStack());
20721
20722   const bool Is64Bit = Subtarget->is64Bit();
20723   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20724
20725   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20726   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20727
20728   // BB:
20729   //  ... [Till the alloca]
20730   // If stacklet is not large enough, jump to mallocMBB
20731   //
20732   // bumpMBB:
20733   //  Allocate by subtracting from RSP
20734   //  Jump to continueMBB
20735   //
20736   // mallocMBB:
20737   //  Allocate by call to runtime
20738   //
20739   // continueMBB:
20740   //  ...
20741   //  [rest of original BB]
20742   //
20743
20744   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20745   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20746   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20747
20748   MachineRegisterInfo &MRI = MF->getRegInfo();
20749   const TargetRegisterClass *AddrRegClass =
20750       getRegClassFor(getPointerTy(MF->getDataLayout()));
20751
20752   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20753     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20754     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20755     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20756     sizeVReg = MI->getOperand(1).getReg(),
20757     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20758
20759   MachineFunction::iterator MBBIter = BB;
20760   ++MBBIter;
20761
20762   MF->insert(MBBIter, bumpMBB);
20763   MF->insert(MBBIter, mallocMBB);
20764   MF->insert(MBBIter, continueMBB);
20765
20766   continueMBB->splice(continueMBB->begin(), BB,
20767                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20768   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20769
20770   // Add code to the main basic block to check if the stack limit has been hit,
20771   // and if so, jump to mallocMBB otherwise to bumpMBB.
20772   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20773   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20774     .addReg(tmpSPVReg).addReg(sizeVReg);
20775   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20776     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20777     .addReg(SPLimitVReg);
20778   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20779
20780   // bumpMBB simply decreases the stack pointer, since we know the current
20781   // stacklet has enough space.
20782   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20783     .addReg(SPLimitVReg);
20784   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20785     .addReg(SPLimitVReg);
20786   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20787
20788   // Calls into a routine in libgcc to allocate more space from the heap.
20789   const uint32_t *RegMask =
20790       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20791   if (IsLP64) {
20792     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20793       .addReg(sizeVReg);
20794     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20795       .addExternalSymbol("__morestack_allocate_stack_space")
20796       .addRegMask(RegMask)
20797       .addReg(X86::RDI, RegState::Implicit)
20798       .addReg(X86::RAX, RegState::ImplicitDefine);
20799   } else if (Is64Bit) {
20800     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20801       .addReg(sizeVReg);
20802     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20803       .addExternalSymbol("__morestack_allocate_stack_space")
20804       .addRegMask(RegMask)
20805       .addReg(X86::EDI, RegState::Implicit)
20806       .addReg(X86::EAX, RegState::ImplicitDefine);
20807   } else {
20808     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20809       .addImm(12);
20810     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20811     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20812       .addExternalSymbol("__morestack_allocate_stack_space")
20813       .addRegMask(RegMask)
20814       .addReg(X86::EAX, RegState::ImplicitDefine);
20815   }
20816
20817   if (!Is64Bit)
20818     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20819       .addImm(16);
20820
20821   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20822     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20823   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20824
20825   // Set up the CFG correctly.
20826   BB->addSuccessor(bumpMBB);
20827   BB->addSuccessor(mallocMBB);
20828   mallocMBB->addSuccessor(continueMBB);
20829   bumpMBB->addSuccessor(continueMBB);
20830
20831   // Take care of the PHI nodes.
20832   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20833           MI->getOperand(0).getReg())
20834     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20835     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20836
20837   // Delete the original pseudo instruction.
20838   MI->eraseFromParent();
20839
20840   // And we're done.
20841   return continueMBB;
20842 }
20843
20844 MachineBasicBlock *
20845 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20846                                         MachineBasicBlock *BB) const {
20847   DebugLoc DL = MI->getDebugLoc();
20848
20849   assert(!Subtarget->isTargetMachO());
20850
20851   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20852                                                     DL);
20853
20854   MI->eraseFromParent();   // The pseudo instruction is gone now.
20855   return BB;
20856 }
20857
20858 MachineBasicBlock *
20859 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20860                                       MachineBasicBlock *BB) const {
20861   // This is pretty easy.  We're taking the value that we received from
20862   // our load from the relocation, sticking it in either RDI (x86-64)
20863   // or EAX and doing an indirect call.  The return value will then
20864   // be in the normal return register.
20865   MachineFunction *F = BB->getParent();
20866   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20867   DebugLoc DL = MI->getDebugLoc();
20868
20869   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20870   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20871
20872   // Get a register mask for the lowered call.
20873   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20874   // proper register mask.
20875   const uint32_t *RegMask =
20876       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20877   if (Subtarget->is64Bit()) {
20878     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20879                                       TII->get(X86::MOV64rm), X86::RDI)
20880     .addReg(X86::RIP)
20881     .addImm(0).addReg(0)
20882     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20883                       MI->getOperand(3).getTargetFlags())
20884     .addReg(0);
20885     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20886     addDirectMem(MIB, X86::RDI);
20887     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20888   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20889     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20890                                       TII->get(X86::MOV32rm), X86::EAX)
20891     .addReg(0)
20892     .addImm(0).addReg(0)
20893     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20894                       MI->getOperand(3).getTargetFlags())
20895     .addReg(0);
20896     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20897     addDirectMem(MIB, X86::EAX);
20898     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20899   } else {
20900     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20901                                       TII->get(X86::MOV32rm), X86::EAX)
20902     .addReg(TII->getGlobalBaseReg(F))
20903     .addImm(0).addReg(0)
20904     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20905                       MI->getOperand(3).getTargetFlags())
20906     .addReg(0);
20907     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20908     addDirectMem(MIB, X86::EAX);
20909     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20910   }
20911
20912   MI->eraseFromParent(); // The pseudo instruction is gone now.
20913   return BB;
20914 }
20915
20916 MachineBasicBlock *
20917 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20918                                     MachineBasicBlock *MBB) const {
20919   DebugLoc DL = MI->getDebugLoc();
20920   MachineFunction *MF = MBB->getParent();
20921   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20922   MachineRegisterInfo &MRI = MF->getRegInfo();
20923
20924   const BasicBlock *BB = MBB->getBasicBlock();
20925   MachineFunction::iterator I = MBB;
20926   ++I;
20927
20928   // Memory Reference
20929   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20930   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20931
20932   unsigned DstReg;
20933   unsigned MemOpndSlot = 0;
20934
20935   unsigned CurOp = 0;
20936
20937   DstReg = MI->getOperand(CurOp++).getReg();
20938   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20939   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20940   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20941   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20942
20943   MemOpndSlot = CurOp;
20944
20945   MVT PVT = getPointerTy(MF->getDataLayout());
20946   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20947          "Invalid Pointer Size!");
20948
20949   // For v = setjmp(buf), we generate
20950   //
20951   // thisMBB:
20952   //  buf[LabelOffset] = restoreMBB
20953   //  SjLjSetup restoreMBB
20954   //
20955   // mainMBB:
20956   //  v_main = 0
20957   //
20958   // sinkMBB:
20959   //  v = phi(main, restore)
20960   //
20961   // restoreMBB:
20962   //  if base pointer being used, load it from frame
20963   //  v_restore = 1
20964
20965   MachineBasicBlock *thisMBB = MBB;
20966   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20967   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20968   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20969   MF->insert(I, mainMBB);
20970   MF->insert(I, sinkMBB);
20971   MF->push_back(restoreMBB);
20972
20973   MachineInstrBuilder MIB;
20974
20975   // Transfer the remainder of BB and its successor edges to sinkMBB.
20976   sinkMBB->splice(sinkMBB->begin(), MBB,
20977                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20978   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20979
20980   // thisMBB:
20981   unsigned PtrStoreOpc = 0;
20982   unsigned LabelReg = 0;
20983   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20984   Reloc::Model RM = MF->getTarget().getRelocationModel();
20985   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20986                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20987
20988   // Prepare IP either in reg or imm.
20989   if (!UseImmLabel) {
20990     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20991     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20992     LabelReg = MRI.createVirtualRegister(PtrRC);
20993     if (Subtarget->is64Bit()) {
20994       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20995               .addReg(X86::RIP)
20996               .addImm(0)
20997               .addReg(0)
20998               .addMBB(restoreMBB)
20999               .addReg(0);
21000     } else {
21001       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21002       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21003               .addReg(XII->getGlobalBaseReg(MF))
21004               .addImm(0)
21005               .addReg(0)
21006               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21007               .addReg(0);
21008     }
21009   } else
21010     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21011   // Store IP
21012   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21013   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21014     if (i == X86::AddrDisp)
21015       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21016     else
21017       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21018   }
21019   if (!UseImmLabel)
21020     MIB.addReg(LabelReg);
21021   else
21022     MIB.addMBB(restoreMBB);
21023   MIB.setMemRefs(MMOBegin, MMOEnd);
21024   // Setup
21025   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21026           .addMBB(restoreMBB);
21027
21028   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21029   MIB.addRegMask(RegInfo->getNoPreservedMask());
21030   thisMBB->addSuccessor(mainMBB);
21031   thisMBB->addSuccessor(restoreMBB);
21032
21033   // mainMBB:
21034   //  EAX = 0
21035   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21036   mainMBB->addSuccessor(sinkMBB);
21037
21038   // sinkMBB:
21039   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21040           TII->get(X86::PHI), DstReg)
21041     .addReg(mainDstReg).addMBB(mainMBB)
21042     .addReg(restoreDstReg).addMBB(restoreMBB);
21043
21044   // restoreMBB:
21045   if (RegInfo->hasBasePointer(*MF)) {
21046     const bool Uses64BitFramePtr =
21047         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21048     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21049     X86FI->setRestoreBasePointer(MF);
21050     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21051     unsigned BasePtr = RegInfo->getBaseRegister();
21052     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21053     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21054                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21055       .setMIFlag(MachineInstr::FrameSetup);
21056   }
21057   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21058   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21059   restoreMBB->addSuccessor(sinkMBB);
21060
21061   MI->eraseFromParent();
21062   return sinkMBB;
21063 }
21064
21065 MachineBasicBlock *
21066 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21067                                      MachineBasicBlock *MBB) const {
21068   DebugLoc DL = MI->getDebugLoc();
21069   MachineFunction *MF = MBB->getParent();
21070   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21071   MachineRegisterInfo &MRI = MF->getRegInfo();
21072
21073   // Memory Reference
21074   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21075   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21076
21077   MVT PVT = getPointerTy(MF->getDataLayout());
21078   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21079          "Invalid Pointer Size!");
21080
21081   const TargetRegisterClass *RC =
21082     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21083   unsigned Tmp = MRI.createVirtualRegister(RC);
21084   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21085   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21086   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21087   unsigned SP = RegInfo->getStackRegister();
21088
21089   MachineInstrBuilder MIB;
21090
21091   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21092   const int64_t SPOffset = 2 * PVT.getStoreSize();
21093
21094   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21095   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21096
21097   // Reload FP
21098   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21099   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21100     MIB.addOperand(MI->getOperand(i));
21101   MIB.setMemRefs(MMOBegin, MMOEnd);
21102   // Reload IP
21103   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21104   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21105     if (i == X86::AddrDisp)
21106       MIB.addDisp(MI->getOperand(i), LabelOffset);
21107     else
21108       MIB.addOperand(MI->getOperand(i));
21109   }
21110   MIB.setMemRefs(MMOBegin, MMOEnd);
21111   // Reload SP
21112   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21113   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21114     if (i == X86::AddrDisp)
21115       MIB.addDisp(MI->getOperand(i), SPOffset);
21116     else
21117       MIB.addOperand(MI->getOperand(i));
21118   }
21119   MIB.setMemRefs(MMOBegin, MMOEnd);
21120   // Jump
21121   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21122
21123   MI->eraseFromParent();
21124   return MBB;
21125 }
21126
21127 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21128 // accumulator loops. Writing back to the accumulator allows the coalescer
21129 // to remove extra copies in the loop.
21130 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21131 MachineBasicBlock *
21132 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21133                                  MachineBasicBlock *MBB) const {
21134   MachineOperand &AddendOp = MI->getOperand(3);
21135
21136   // Bail out early if the addend isn't a register - we can't switch these.
21137   if (!AddendOp.isReg())
21138     return MBB;
21139
21140   MachineFunction &MF = *MBB->getParent();
21141   MachineRegisterInfo &MRI = MF.getRegInfo();
21142
21143   // Check whether the addend is defined by a PHI:
21144   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21145   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21146   if (!AddendDef.isPHI())
21147     return MBB;
21148
21149   // Look for the following pattern:
21150   // loop:
21151   //   %addend = phi [%entry, 0], [%loop, %result]
21152   //   ...
21153   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21154
21155   // Replace with:
21156   //   loop:
21157   //   %addend = phi [%entry, 0], [%loop, %result]
21158   //   ...
21159   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21160
21161   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21162     assert(AddendDef.getOperand(i).isReg());
21163     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21164     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21165     if (&PHISrcInst == MI) {
21166       // Found a matching instruction.
21167       unsigned NewFMAOpc = 0;
21168       switch (MI->getOpcode()) {
21169         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21170         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21171         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21172         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21173         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21174         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21175         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21176         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21177         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21178         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21179         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21180         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21181         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21182         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21183         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21184         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21185         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21186         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21187         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21188         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21189
21190         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21191         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21192         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21193         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21194         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21195         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21196         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21197         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21198         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21199         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21200         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21201         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21202         default: llvm_unreachable("Unrecognized FMA variant.");
21203       }
21204
21205       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21206       MachineInstrBuilder MIB =
21207         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21208         .addOperand(MI->getOperand(0))
21209         .addOperand(MI->getOperand(3))
21210         .addOperand(MI->getOperand(2))
21211         .addOperand(MI->getOperand(1));
21212       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21213       MI->eraseFromParent();
21214     }
21215   }
21216
21217   return MBB;
21218 }
21219
21220 MachineBasicBlock *
21221 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21222                                                MachineBasicBlock *BB) const {
21223   switch (MI->getOpcode()) {
21224   default: llvm_unreachable("Unexpected instr type to insert");
21225   case X86::TAILJMPd64:
21226   case X86::TAILJMPr64:
21227   case X86::TAILJMPm64:
21228   case X86::TAILJMPd64_REX:
21229   case X86::TAILJMPr64_REX:
21230   case X86::TAILJMPm64_REX:
21231     llvm_unreachable("TAILJMP64 would not be touched here.");
21232   case X86::TCRETURNdi64:
21233   case X86::TCRETURNri64:
21234   case X86::TCRETURNmi64:
21235     return BB;
21236   case X86::WIN_ALLOCA:
21237     return EmitLoweredWinAlloca(MI, BB);
21238   case X86::SEG_ALLOCA_32:
21239   case X86::SEG_ALLOCA_64:
21240     return EmitLoweredSegAlloca(MI, BB);
21241   case X86::TLSCall_32:
21242   case X86::TLSCall_64:
21243     return EmitLoweredTLSCall(MI, BB);
21244   case X86::CMOV_FR32:
21245   case X86::CMOV_FR64:
21246   case X86::CMOV_GR8:
21247   case X86::CMOV_GR16:
21248   case X86::CMOV_GR32:
21249   case X86::CMOV_RFP32:
21250   case X86::CMOV_RFP64:
21251   case X86::CMOV_RFP80:
21252   case X86::CMOV_V2F64:
21253   case X86::CMOV_V2I64:
21254   case X86::CMOV_V4F32:
21255   case X86::CMOV_V4F64:
21256   case X86::CMOV_V4I64:
21257   case X86::CMOV_V16F32:
21258   case X86::CMOV_V8F32:
21259   case X86::CMOV_V8F64:
21260   case X86::CMOV_V8I64:
21261   case X86::CMOV_V8I1:
21262   case X86::CMOV_V16I1:
21263   case X86::CMOV_V32I1:
21264   case X86::CMOV_V64I1:
21265     return EmitLoweredSelect(MI, BB);
21266
21267   case X86::RELEASE_FADD32mr:
21268   case X86::RELEASE_FADD64mr:
21269     return EmitLoweredAtomicFP(MI, BB);
21270
21271   case X86::FP32_TO_INT16_IN_MEM:
21272   case X86::FP32_TO_INT32_IN_MEM:
21273   case X86::FP32_TO_INT64_IN_MEM:
21274   case X86::FP64_TO_INT16_IN_MEM:
21275   case X86::FP64_TO_INT32_IN_MEM:
21276   case X86::FP64_TO_INT64_IN_MEM:
21277   case X86::FP80_TO_INT16_IN_MEM:
21278   case X86::FP80_TO_INT32_IN_MEM:
21279   case X86::FP80_TO_INT64_IN_MEM: {
21280     MachineFunction *F = BB->getParent();
21281     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21282     DebugLoc DL = MI->getDebugLoc();
21283
21284     // Change the floating point control register to use "round towards zero"
21285     // mode when truncating to an integer value.
21286     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21287     addFrameReference(BuildMI(*BB, MI, DL,
21288                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21289
21290     // Load the old value of the high byte of the control word...
21291     unsigned OldCW =
21292       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21293     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21294                       CWFrameIdx);
21295
21296     // Set the high part to be round to zero...
21297     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21298       .addImm(0xC7F);
21299
21300     // Reload the modified control word now...
21301     addFrameReference(BuildMI(*BB, MI, DL,
21302                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21303
21304     // Restore the memory image of control word to original value
21305     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21306       .addReg(OldCW);
21307
21308     // Get the X86 opcode to use.
21309     unsigned Opc;
21310     switch (MI->getOpcode()) {
21311     default: llvm_unreachable("illegal opcode!");
21312     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21313     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21314     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21315     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21316     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21317     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21318     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21319     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21320     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21321     }
21322
21323     X86AddressMode AM;
21324     MachineOperand &Op = MI->getOperand(0);
21325     if (Op.isReg()) {
21326       AM.BaseType = X86AddressMode::RegBase;
21327       AM.Base.Reg = Op.getReg();
21328     } else {
21329       AM.BaseType = X86AddressMode::FrameIndexBase;
21330       AM.Base.FrameIndex = Op.getIndex();
21331     }
21332     Op = MI->getOperand(1);
21333     if (Op.isImm())
21334       AM.Scale = Op.getImm();
21335     Op = MI->getOperand(2);
21336     if (Op.isImm())
21337       AM.IndexReg = Op.getImm();
21338     Op = MI->getOperand(3);
21339     if (Op.isGlobal()) {
21340       AM.GV = Op.getGlobal();
21341     } else {
21342       AM.Disp = Op.getImm();
21343     }
21344     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21345                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21346
21347     // Reload the original control word now.
21348     addFrameReference(BuildMI(*BB, MI, DL,
21349                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21350
21351     MI->eraseFromParent();   // The pseudo instruction is gone now.
21352     return BB;
21353   }
21354     // String/text processing lowering.
21355   case X86::PCMPISTRM128REG:
21356   case X86::VPCMPISTRM128REG:
21357   case X86::PCMPISTRM128MEM:
21358   case X86::VPCMPISTRM128MEM:
21359   case X86::PCMPESTRM128REG:
21360   case X86::VPCMPESTRM128REG:
21361   case X86::PCMPESTRM128MEM:
21362   case X86::VPCMPESTRM128MEM:
21363     assert(Subtarget->hasSSE42() &&
21364            "Target must have SSE4.2 or AVX features enabled");
21365     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21366
21367   // String/text processing lowering.
21368   case X86::PCMPISTRIREG:
21369   case X86::VPCMPISTRIREG:
21370   case X86::PCMPISTRIMEM:
21371   case X86::VPCMPISTRIMEM:
21372   case X86::PCMPESTRIREG:
21373   case X86::VPCMPESTRIREG:
21374   case X86::PCMPESTRIMEM:
21375   case X86::VPCMPESTRIMEM:
21376     assert(Subtarget->hasSSE42() &&
21377            "Target must have SSE4.2 or AVX features enabled");
21378     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21379
21380   // Thread synchronization.
21381   case X86::MONITOR:
21382     return EmitMonitor(MI, BB, Subtarget);
21383
21384   // xbegin
21385   case X86::XBEGIN:
21386     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21387
21388   case X86::VASTART_SAVE_XMM_REGS:
21389     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21390
21391   case X86::VAARG_64:
21392     return EmitVAARG64WithCustomInserter(MI, BB);
21393
21394   case X86::EH_SjLj_SetJmp32:
21395   case X86::EH_SjLj_SetJmp64:
21396     return emitEHSjLjSetJmp(MI, BB);
21397
21398   case X86::EH_SjLj_LongJmp32:
21399   case X86::EH_SjLj_LongJmp64:
21400     return emitEHSjLjLongJmp(MI, BB);
21401
21402   case TargetOpcode::STATEPOINT:
21403     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21404     // this point in the process.  We diverge later.
21405     return emitPatchPoint(MI, BB);
21406
21407   case TargetOpcode::STACKMAP:
21408   case TargetOpcode::PATCHPOINT:
21409     return emitPatchPoint(MI, BB);
21410
21411   case X86::VFMADDPDr213r:
21412   case X86::VFMADDPSr213r:
21413   case X86::VFMADDSDr213r:
21414   case X86::VFMADDSSr213r:
21415   case X86::VFMSUBPDr213r:
21416   case X86::VFMSUBPSr213r:
21417   case X86::VFMSUBSDr213r:
21418   case X86::VFMSUBSSr213r:
21419   case X86::VFNMADDPDr213r:
21420   case X86::VFNMADDPSr213r:
21421   case X86::VFNMADDSDr213r:
21422   case X86::VFNMADDSSr213r:
21423   case X86::VFNMSUBPDr213r:
21424   case X86::VFNMSUBPSr213r:
21425   case X86::VFNMSUBSDr213r:
21426   case X86::VFNMSUBSSr213r:
21427   case X86::VFMADDSUBPDr213r:
21428   case X86::VFMADDSUBPSr213r:
21429   case X86::VFMSUBADDPDr213r:
21430   case X86::VFMSUBADDPSr213r:
21431   case X86::VFMADDPDr213rY:
21432   case X86::VFMADDPSr213rY:
21433   case X86::VFMSUBPDr213rY:
21434   case X86::VFMSUBPSr213rY:
21435   case X86::VFNMADDPDr213rY:
21436   case X86::VFNMADDPSr213rY:
21437   case X86::VFNMSUBPDr213rY:
21438   case X86::VFNMSUBPSr213rY:
21439   case X86::VFMADDSUBPDr213rY:
21440   case X86::VFMADDSUBPSr213rY:
21441   case X86::VFMSUBADDPDr213rY:
21442   case X86::VFMSUBADDPSr213rY:
21443     return emitFMA3Instr(MI, BB);
21444   }
21445 }
21446
21447 //===----------------------------------------------------------------------===//
21448 //                           X86 Optimization Hooks
21449 //===----------------------------------------------------------------------===//
21450
21451 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21452                                                       APInt &KnownZero,
21453                                                       APInt &KnownOne,
21454                                                       const SelectionDAG &DAG,
21455                                                       unsigned Depth) const {
21456   unsigned BitWidth = KnownZero.getBitWidth();
21457   unsigned Opc = Op.getOpcode();
21458   assert((Opc >= ISD::BUILTIN_OP_END ||
21459           Opc == ISD::INTRINSIC_WO_CHAIN ||
21460           Opc == ISD::INTRINSIC_W_CHAIN ||
21461           Opc == ISD::INTRINSIC_VOID) &&
21462          "Should use MaskedValueIsZero if you don't know whether Op"
21463          " is a target node!");
21464
21465   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21466   switch (Opc) {
21467   default: break;
21468   case X86ISD::ADD:
21469   case X86ISD::SUB:
21470   case X86ISD::ADC:
21471   case X86ISD::SBB:
21472   case X86ISD::SMUL:
21473   case X86ISD::UMUL:
21474   case X86ISD::INC:
21475   case X86ISD::DEC:
21476   case X86ISD::OR:
21477   case X86ISD::XOR:
21478   case X86ISD::AND:
21479     // These nodes' second result is a boolean.
21480     if (Op.getResNo() == 0)
21481       break;
21482     // Fallthrough
21483   case X86ISD::SETCC:
21484     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21485     break;
21486   case ISD::INTRINSIC_WO_CHAIN: {
21487     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21488     unsigned NumLoBits = 0;
21489     switch (IntId) {
21490     default: break;
21491     case Intrinsic::x86_sse_movmsk_ps:
21492     case Intrinsic::x86_avx_movmsk_ps_256:
21493     case Intrinsic::x86_sse2_movmsk_pd:
21494     case Intrinsic::x86_avx_movmsk_pd_256:
21495     case Intrinsic::x86_mmx_pmovmskb:
21496     case Intrinsic::x86_sse2_pmovmskb_128:
21497     case Intrinsic::x86_avx2_pmovmskb: {
21498       // High bits of movmskp{s|d}, pmovmskb are known zero.
21499       switch (IntId) {
21500         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21501         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21502         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21503         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21504         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21505         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21506         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21507         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21508       }
21509       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21510       break;
21511     }
21512     }
21513     break;
21514   }
21515   }
21516 }
21517
21518 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21519   SDValue Op,
21520   const SelectionDAG &,
21521   unsigned Depth) const {
21522   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21523   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21524     return Op.getValueType().getScalarType().getSizeInBits();
21525
21526   // Fallback case.
21527   return 1;
21528 }
21529
21530 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21531 /// node is a GlobalAddress + offset.
21532 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21533                                        const GlobalValue* &GA,
21534                                        int64_t &Offset) const {
21535   if (N->getOpcode() == X86ISD::Wrapper) {
21536     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21537       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21538       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21539       return true;
21540     }
21541   }
21542   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21543 }
21544
21545 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21546 /// same as extracting the high 128-bit part of 256-bit vector and then
21547 /// inserting the result into the low part of a new 256-bit vector
21548 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21549   EVT VT = SVOp->getValueType(0);
21550   unsigned NumElems = VT.getVectorNumElements();
21551
21552   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21553   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21554     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21555         SVOp->getMaskElt(j) >= 0)
21556       return false;
21557
21558   return true;
21559 }
21560
21561 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21562 /// same as extracting the low 128-bit part of 256-bit vector and then
21563 /// inserting the result into the high part of a new 256-bit vector
21564 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21565   EVT VT = SVOp->getValueType(0);
21566   unsigned NumElems = VT.getVectorNumElements();
21567
21568   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21569   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21570     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21571         SVOp->getMaskElt(j) >= 0)
21572       return false;
21573
21574   return true;
21575 }
21576
21577 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21578 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21579                                         TargetLowering::DAGCombinerInfo &DCI,
21580                                         const X86Subtarget* Subtarget) {
21581   SDLoc dl(N);
21582   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21583   SDValue V1 = SVOp->getOperand(0);
21584   SDValue V2 = SVOp->getOperand(1);
21585   EVT VT = SVOp->getValueType(0);
21586   unsigned NumElems = VT.getVectorNumElements();
21587
21588   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21589       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21590     //
21591     //                   0,0,0,...
21592     //                      |
21593     //    V      UNDEF    BUILD_VECTOR    UNDEF
21594     //     \      /           \           /
21595     //  CONCAT_VECTOR         CONCAT_VECTOR
21596     //         \                  /
21597     //          \                /
21598     //          RESULT: V + zero extended
21599     //
21600     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21601         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21602         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21603       return SDValue();
21604
21605     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21606       return SDValue();
21607
21608     // To match the shuffle mask, the first half of the mask should
21609     // be exactly the first vector, and all the rest a splat with the
21610     // first element of the second one.
21611     for (unsigned i = 0; i != NumElems/2; ++i)
21612       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21613           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21614         return SDValue();
21615
21616     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21617     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21618       if (Ld->hasNUsesOfValue(1, 0)) {
21619         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21620         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21621         SDValue ResNode =
21622           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21623                                   Ld->getMemoryVT(),
21624                                   Ld->getPointerInfo(),
21625                                   Ld->getAlignment(),
21626                                   false/*isVolatile*/, true/*ReadMem*/,
21627                                   false/*WriteMem*/);
21628
21629         // Make sure the newly-created LOAD is in the same position as Ld in
21630         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21631         // and update uses of Ld's output chain to use the TokenFactor.
21632         if (Ld->hasAnyUseOfValue(1)) {
21633           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21634                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21635           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21636           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21637                                  SDValue(ResNode.getNode(), 1));
21638         }
21639
21640         return DAG.getBitcast(VT, ResNode);
21641       }
21642     }
21643
21644     // Emit a zeroed vector and insert the desired subvector on its
21645     // first half.
21646     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21647     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21648     return DCI.CombineTo(N, InsV);
21649   }
21650
21651   //===--------------------------------------------------------------------===//
21652   // Combine some shuffles into subvector extracts and inserts:
21653   //
21654
21655   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21656   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21657     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21658     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21659     return DCI.CombineTo(N, InsV);
21660   }
21661
21662   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21663   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21664     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21665     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21666     return DCI.CombineTo(N, InsV);
21667   }
21668
21669   return SDValue();
21670 }
21671
21672 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21673 /// possible.
21674 ///
21675 /// This is the leaf of the recursive combinine below. When we have found some
21676 /// chain of single-use x86 shuffle instructions and accumulated the combined
21677 /// shuffle mask represented by them, this will try to pattern match that mask
21678 /// into either a single instruction if there is a special purpose instruction
21679 /// for this operation, or into a PSHUFB instruction which is a fully general
21680 /// instruction but should only be used to replace chains over a certain depth.
21681 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21682                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21683                                    TargetLowering::DAGCombinerInfo &DCI,
21684                                    const X86Subtarget *Subtarget) {
21685   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21686
21687   // Find the operand that enters the chain. Note that multiple uses are OK
21688   // here, we're not going to remove the operand we find.
21689   SDValue Input = Op.getOperand(0);
21690   while (Input.getOpcode() == ISD::BITCAST)
21691     Input = Input.getOperand(0);
21692
21693   MVT VT = Input.getSimpleValueType();
21694   MVT RootVT = Root.getSimpleValueType();
21695   SDLoc DL(Root);
21696
21697   // Just remove no-op shuffle masks.
21698   if (Mask.size() == 1) {
21699     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21700                   /*AddTo*/ true);
21701     return true;
21702   }
21703
21704   // Use the float domain if the operand type is a floating point type.
21705   bool FloatDomain = VT.isFloatingPoint();
21706
21707   // For floating point shuffles, we don't have free copies in the shuffle
21708   // instructions or the ability to load as part of the instruction, so
21709   // canonicalize their shuffles to UNPCK or MOV variants.
21710   //
21711   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21712   // vectors because it can have a load folded into it that UNPCK cannot. This
21713   // doesn't preclude something switching to the shorter encoding post-RA.
21714   //
21715   // FIXME: Should teach these routines about AVX vector widths.
21716   if (FloatDomain && VT.getSizeInBits() == 128) {
21717     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21718       bool Lo = Mask.equals({0, 0});
21719       unsigned Shuffle;
21720       MVT ShuffleVT;
21721       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21722       // is no slower than UNPCKLPD but has the option to fold the input operand
21723       // into even an unaligned memory load.
21724       if (Lo && Subtarget->hasSSE3()) {
21725         Shuffle = X86ISD::MOVDDUP;
21726         ShuffleVT = MVT::v2f64;
21727       } else {
21728         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21729         // than the UNPCK variants.
21730         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21731         ShuffleVT = MVT::v4f32;
21732       }
21733       if (Depth == 1 && Root->getOpcode() == Shuffle)
21734         return false; // Nothing to do!
21735       Op = DAG.getBitcast(ShuffleVT, Input);
21736       DCI.AddToWorklist(Op.getNode());
21737       if (Shuffle == X86ISD::MOVDDUP)
21738         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21739       else
21740         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21741       DCI.AddToWorklist(Op.getNode());
21742       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21743                     /*AddTo*/ true);
21744       return true;
21745     }
21746     if (Subtarget->hasSSE3() &&
21747         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21748       bool Lo = Mask.equals({0, 0, 2, 2});
21749       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21750       MVT ShuffleVT = MVT::v4f32;
21751       if (Depth == 1 && Root->getOpcode() == Shuffle)
21752         return false; // Nothing to do!
21753       Op = DAG.getBitcast(ShuffleVT, Input);
21754       DCI.AddToWorklist(Op.getNode());
21755       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21756       DCI.AddToWorklist(Op.getNode());
21757       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21758                     /*AddTo*/ true);
21759       return true;
21760     }
21761     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21762       bool Lo = Mask.equals({0, 0, 1, 1});
21763       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21764       MVT ShuffleVT = MVT::v4f32;
21765       if (Depth == 1 && Root->getOpcode() == Shuffle)
21766         return false; // Nothing to do!
21767       Op = DAG.getBitcast(ShuffleVT, Input);
21768       DCI.AddToWorklist(Op.getNode());
21769       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21770       DCI.AddToWorklist(Op.getNode());
21771       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21772                     /*AddTo*/ true);
21773       return true;
21774     }
21775   }
21776
21777   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21778   // variants as none of these have single-instruction variants that are
21779   // superior to the UNPCK formulation.
21780   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21781       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21782        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21783        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21784        Mask.equals(
21785            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21786     bool Lo = Mask[0] == 0;
21787     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21788     if (Depth == 1 && Root->getOpcode() == Shuffle)
21789       return false; // Nothing to do!
21790     MVT ShuffleVT;
21791     switch (Mask.size()) {
21792     case 8:
21793       ShuffleVT = MVT::v8i16;
21794       break;
21795     case 16:
21796       ShuffleVT = MVT::v16i8;
21797       break;
21798     default:
21799       llvm_unreachable("Impossible mask size!");
21800     };
21801     Op = DAG.getBitcast(ShuffleVT, Input);
21802     DCI.AddToWorklist(Op.getNode());
21803     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21804     DCI.AddToWorklist(Op.getNode());
21805     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21806                   /*AddTo*/ true);
21807     return true;
21808   }
21809
21810   // Don't try to re-form single instruction chains under any circumstances now
21811   // that we've done encoding canonicalization for them.
21812   if (Depth < 2)
21813     return false;
21814
21815   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21816   // can replace them with a single PSHUFB instruction profitably. Intel's
21817   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21818   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21819   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21820     SmallVector<SDValue, 16> PSHUFBMask;
21821     int NumBytes = VT.getSizeInBits() / 8;
21822     int Ratio = NumBytes / Mask.size();
21823     for (int i = 0; i < NumBytes; ++i) {
21824       if (Mask[i / Ratio] == SM_SentinelUndef) {
21825         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21826         continue;
21827       }
21828       int M = Mask[i / Ratio] != SM_SentinelZero
21829                   ? Ratio * Mask[i / Ratio] + i % Ratio
21830                   : 255;
21831       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21832     }
21833     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21834     Op = DAG.getBitcast(ByteVT, Input);
21835     DCI.AddToWorklist(Op.getNode());
21836     SDValue PSHUFBMaskOp =
21837         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21838     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21839     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21840     DCI.AddToWorklist(Op.getNode());
21841     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21842                   /*AddTo*/ true);
21843     return true;
21844   }
21845
21846   // Failed to find any combines.
21847   return false;
21848 }
21849
21850 /// \brief Fully generic combining of x86 shuffle instructions.
21851 ///
21852 /// This should be the last combine run over the x86 shuffle instructions. Once
21853 /// they have been fully optimized, this will recursively consider all chains
21854 /// of single-use shuffle instructions, build a generic model of the cumulative
21855 /// shuffle operation, and check for simpler instructions which implement this
21856 /// operation. We use this primarily for two purposes:
21857 ///
21858 /// 1) Collapse generic shuffles to specialized single instructions when
21859 ///    equivalent. In most cases, this is just an encoding size win, but
21860 ///    sometimes we will collapse multiple generic shuffles into a single
21861 ///    special-purpose shuffle.
21862 /// 2) Look for sequences of shuffle instructions with 3 or more total
21863 ///    instructions, and replace them with the slightly more expensive SSSE3
21864 ///    PSHUFB instruction if available. We do this as the last combining step
21865 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21866 ///    a suitable short sequence of other instructions. The PHUFB will either
21867 ///    use a register or have to read from memory and so is slightly (but only
21868 ///    slightly) more expensive than the other shuffle instructions.
21869 ///
21870 /// Because this is inherently a quadratic operation (for each shuffle in
21871 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21872 /// This should never be an issue in practice as the shuffle lowering doesn't
21873 /// produce sequences of more than 8 instructions.
21874 ///
21875 /// FIXME: We will currently miss some cases where the redundant shuffling
21876 /// would simplify under the threshold for PSHUFB formation because of
21877 /// combine-ordering. To fix this, we should do the redundant instruction
21878 /// combining in this recursive walk.
21879 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21880                                           ArrayRef<int> RootMask,
21881                                           int Depth, bool HasPSHUFB,
21882                                           SelectionDAG &DAG,
21883                                           TargetLowering::DAGCombinerInfo &DCI,
21884                                           const X86Subtarget *Subtarget) {
21885   // Bound the depth of our recursive combine because this is ultimately
21886   // quadratic in nature.
21887   if (Depth > 8)
21888     return false;
21889
21890   // Directly rip through bitcasts to find the underlying operand.
21891   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21892     Op = Op.getOperand(0);
21893
21894   MVT VT = Op.getSimpleValueType();
21895   if (!VT.isVector())
21896     return false; // Bail if we hit a non-vector.
21897
21898   assert(Root.getSimpleValueType().isVector() &&
21899          "Shuffles operate on vector types!");
21900   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21901          "Can only combine shuffles of the same vector register size.");
21902
21903   if (!isTargetShuffle(Op.getOpcode()))
21904     return false;
21905   SmallVector<int, 16> OpMask;
21906   bool IsUnary;
21907   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21908   // We only can combine unary shuffles which we can decode the mask for.
21909   if (!HaveMask || !IsUnary)
21910     return false;
21911
21912   assert(VT.getVectorNumElements() == OpMask.size() &&
21913          "Different mask size from vector size!");
21914   assert(((RootMask.size() > OpMask.size() &&
21915            RootMask.size() % OpMask.size() == 0) ||
21916           (OpMask.size() > RootMask.size() &&
21917            OpMask.size() % RootMask.size() == 0) ||
21918           OpMask.size() == RootMask.size()) &&
21919          "The smaller number of elements must divide the larger.");
21920   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21921   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21922   assert(((RootRatio == 1 && OpRatio == 1) ||
21923           (RootRatio == 1) != (OpRatio == 1)) &&
21924          "Must not have a ratio for both incoming and op masks!");
21925
21926   SmallVector<int, 16> Mask;
21927   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21928
21929   // Merge this shuffle operation's mask into our accumulated mask. Note that
21930   // this shuffle's mask will be the first applied to the input, followed by the
21931   // root mask to get us all the way to the root value arrangement. The reason
21932   // for this order is that we are recursing up the operation chain.
21933   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21934     int RootIdx = i / RootRatio;
21935     if (RootMask[RootIdx] < 0) {
21936       // This is a zero or undef lane, we're done.
21937       Mask.push_back(RootMask[RootIdx]);
21938       continue;
21939     }
21940
21941     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21942     int OpIdx = RootMaskedIdx / OpRatio;
21943     if (OpMask[OpIdx] < 0) {
21944       // The incoming lanes are zero or undef, it doesn't matter which ones we
21945       // are using.
21946       Mask.push_back(OpMask[OpIdx]);
21947       continue;
21948     }
21949
21950     // Ok, we have non-zero lanes, map them through.
21951     Mask.push_back(OpMask[OpIdx] * OpRatio +
21952                    RootMaskedIdx % OpRatio);
21953   }
21954
21955   // See if we can recurse into the operand to combine more things.
21956   switch (Op.getOpcode()) {
21957     case X86ISD::PSHUFB:
21958       HasPSHUFB = true;
21959     case X86ISD::PSHUFD:
21960     case X86ISD::PSHUFHW:
21961     case X86ISD::PSHUFLW:
21962       if (Op.getOperand(0).hasOneUse() &&
21963           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21964                                         HasPSHUFB, DAG, DCI, Subtarget))
21965         return true;
21966       break;
21967
21968     case X86ISD::UNPCKL:
21969     case X86ISD::UNPCKH:
21970       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21971       // We can't check for single use, we have to check that this shuffle is the only user.
21972       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21973           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21974                                         HasPSHUFB, DAG, DCI, Subtarget))
21975           return true;
21976       break;
21977   }
21978
21979   // Minor canonicalization of the accumulated shuffle mask to make it easier
21980   // to match below. All this does is detect masks with squential pairs of
21981   // elements, and shrink them to the half-width mask. It does this in a loop
21982   // so it will reduce the size of the mask to the minimal width mask which
21983   // performs an equivalent shuffle.
21984   SmallVector<int, 16> WidenedMask;
21985   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21986     Mask = std::move(WidenedMask);
21987     WidenedMask.clear();
21988   }
21989
21990   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21991                                 Subtarget);
21992 }
21993
21994 /// \brief Get the PSHUF-style mask from PSHUF node.
21995 ///
21996 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21997 /// PSHUF-style masks that can be reused with such instructions.
21998 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21999   MVT VT = N.getSimpleValueType();
22000   SmallVector<int, 4> Mask;
22001   bool IsUnary;
22002   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22003   (void)HaveMask;
22004   assert(HaveMask);
22005
22006   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22007   // matter. Check that the upper masks are repeats and remove them.
22008   if (VT.getSizeInBits() > 128) {
22009     int LaneElts = 128 / VT.getScalarSizeInBits();
22010 #ifndef NDEBUG
22011     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22012       for (int j = 0; j < LaneElts; ++j)
22013         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22014                "Mask doesn't repeat in high 128-bit lanes!");
22015 #endif
22016     Mask.resize(LaneElts);
22017   }
22018
22019   switch (N.getOpcode()) {
22020   case X86ISD::PSHUFD:
22021     return Mask;
22022   case X86ISD::PSHUFLW:
22023     Mask.resize(4);
22024     return Mask;
22025   case X86ISD::PSHUFHW:
22026     Mask.erase(Mask.begin(), Mask.begin() + 4);
22027     for (int &M : Mask)
22028       M -= 4;
22029     return Mask;
22030   default:
22031     llvm_unreachable("No valid shuffle instruction found!");
22032   }
22033 }
22034
22035 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22036 ///
22037 /// We walk up the chain and look for a combinable shuffle, skipping over
22038 /// shuffles that we could hoist this shuffle's transformation past without
22039 /// altering anything.
22040 static SDValue
22041 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22042                              SelectionDAG &DAG,
22043                              TargetLowering::DAGCombinerInfo &DCI) {
22044   assert(N.getOpcode() == X86ISD::PSHUFD &&
22045          "Called with something other than an x86 128-bit half shuffle!");
22046   SDLoc DL(N);
22047
22048   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22049   // of the shuffles in the chain so that we can form a fresh chain to replace
22050   // this one.
22051   SmallVector<SDValue, 8> Chain;
22052   SDValue V = N.getOperand(0);
22053   for (; V.hasOneUse(); V = V.getOperand(0)) {
22054     switch (V.getOpcode()) {
22055     default:
22056       return SDValue(); // Nothing combined!
22057
22058     case ISD::BITCAST:
22059       // Skip bitcasts as we always know the type for the target specific
22060       // instructions.
22061       continue;
22062
22063     case X86ISD::PSHUFD:
22064       // Found another dword shuffle.
22065       break;
22066
22067     case X86ISD::PSHUFLW:
22068       // Check that the low words (being shuffled) are the identity in the
22069       // dword shuffle, and the high words are self-contained.
22070       if (Mask[0] != 0 || Mask[1] != 1 ||
22071           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22072         return SDValue();
22073
22074       Chain.push_back(V);
22075       continue;
22076
22077     case X86ISD::PSHUFHW:
22078       // Check that the high words (being shuffled) are the identity in the
22079       // dword shuffle, and the low words are self-contained.
22080       if (Mask[2] != 2 || Mask[3] != 3 ||
22081           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22082         return SDValue();
22083
22084       Chain.push_back(V);
22085       continue;
22086
22087     case X86ISD::UNPCKL:
22088     case X86ISD::UNPCKH:
22089       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22090       // shuffle into a preceding word shuffle.
22091       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22092           V.getSimpleValueType().getScalarType() != MVT::i16)
22093         return SDValue();
22094
22095       // Search for a half-shuffle which we can combine with.
22096       unsigned CombineOp =
22097           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22098       if (V.getOperand(0) != V.getOperand(1) ||
22099           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22100         return SDValue();
22101       Chain.push_back(V);
22102       V = V.getOperand(0);
22103       do {
22104         switch (V.getOpcode()) {
22105         default:
22106           return SDValue(); // Nothing to combine.
22107
22108         case X86ISD::PSHUFLW:
22109         case X86ISD::PSHUFHW:
22110           if (V.getOpcode() == CombineOp)
22111             break;
22112
22113           Chain.push_back(V);
22114
22115           // Fallthrough!
22116         case ISD::BITCAST:
22117           V = V.getOperand(0);
22118           continue;
22119         }
22120         break;
22121       } while (V.hasOneUse());
22122       break;
22123     }
22124     // Break out of the loop if we break out of the switch.
22125     break;
22126   }
22127
22128   if (!V.hasOneUse())
22129     // We fell out of the loop without finding a viable combining instruction.
22130     return SDValue();
22131
22132   // Merge this node's mask and our incoming mask.
22133   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22134   for (int &M : Mask)
22135     M = VMask[M];
22136   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22137                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22138
22139   // Rebuild the chain around this new shuffle.
22140   while (!Chain.empty()) {
22141     SDValue W = Chain.pop_back_val();
22142
22143     if (V.getValueType() != W.getOperand(0).getValueType())
22144       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22145
22146     switch (W.getOpcode()) {
22147     default:
22148       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22149
22150     case X86ISD::UNPCKL:
22151     case X86ISD::UNPCKH:
22152       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22153       break;
22154
22155     case X86ISD::PSHUFD:
22156     case X86ISD::PSHUFLW:
22157     case X86ISD::PSHUFHW:
22158       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22159       break;
22160     }
22161   }
22162   if (V.getValueType() != N.getValueType())
22163     V = DAG.getBitcast(N.getValueType(), V);
22164
22165   // Return the new chain to replace N.
22166   return V;
22167 }
22168
22169 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22170 ///
22171 /// We walk up the chain, skipping shuffles of the other half and looking
22172 /// through shuffles which switch halves trying to find a shuffle of the same
22173 /// pair of dwords.
22174 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22175                                         SelectionDAG &DAG,
22176                                         TargetLowering::DAGCombinerInfo &DCI) {
22177   assert(
22178       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22179       "Called with something other than an x86 128-bit half shuffle!");
22180   SDLoc DL(N);
22181   unsigned CombineOpcode = N.getOpcode();
22182
22183   // Walk up a single-use chain looking for a combinable shuffle.
22184   SDValue V = N.getOperand(0);
22185   for (; V.hasOneUse(); V = V.getOperand(0)) {
22186     switch (V.getOpcode()) {
22187     default:
22188       return false; // Nothing combined!
22189
22190     case ISD::BITCAST:
22191       // Skip bitcasts as we always know the type for the target specific
22192       // instructions.
22193       continue;
22194
22195     case X86ISD::PSHUFLW:
22196     case X86ISD::PSHUFHW:
22197       if (V.getOpcode() == CombineOpcode)
22198         break;
22199
22200       // Other-half shuffles are no-ops.
22201       continue;
22202     }
22203     // Break out of the loop if we break out of the switch.
22204     break;
22205   }
22206
22207   if (!V.hasOneUse())
22208     // We fell out of the loop without finding a viable combining instruction.
22209     return false;
22210
22211   // Combine away the bottom node as its shuffle will be accumulated into
22212   // a preceding shuffle.
22213   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22214
22215   // Record the old value.
22216   SDValue Old = V;
22217
22218   // Merge this node's mask and our incoming mask (adjusted to account for all
22219   // the pshufd instructions encountered).
22220   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22221   for (int &M : Mask)
22222     M = VMask[M];
22223   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22224                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22225
22226   // Check that the shuffles didn't cancel each other out. If not, we need to
22227   // combine to the new one.
22228   if (Old != V)
22229     // Replace the combinable shuffle with the combined one, updating all users
22230     // so that we re-evaluate the chain here.
22231     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22232
22233   return true;
22234 }
22235
22236 /// \brief Try to combine x86 target specific shuffles.
22237 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22238                                            TargetLowering::DAGCombinerInfo &DCI,
22239                                            const X86Subtarget *Subtarget) {
22240   SDLoc DL(N);
22241   MVT VT = N.getSimpleValueType();
22242   SmallVector<int, 4> Mask;
22243
22244   switch (N.getOpcode()) {
22245   case X86ISD::PSHUFD:
22246   case X86ISD::PSHUFLW:
22247   case X86ISD::PSHUFHW:
22248     Mask = getPSHUFShuffleMask(N);
22249     assert(Mask.size() == 4);
22250     break;
22251   default:
22252     return SDValue();
22253   }
22254
22255   // Nuke no-op shuffles that show up after combining.
22256   if (isNoopShuffleMask(Mask))
22257     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22258
22259   // Look for simplifications involving one or two shuffle instructions.
22260   SDValue V = N.getOperand(0);
22261   switch (N.getOpcode()) {
22262   default:
22263     break;
22264   case X86ISD::PSHUFLW:
22265   case X86ISD::PSHUFHW:
22266     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22267
22268     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22269       return SDValue(); // We combined away this shuffle, so we're done.
22270
22271     // See if this reduces to a PSHUFD which is no more expensive and can
22272     // combine with more operations. Note that it has to at least flip the
22273     // dwords as otherwise it would have been removed as a no-op.
22274     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22275       int DMask[] = {0, 1, 2, 3};
22276       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22277       DMask[DOffset + 0] = DOffset + 1;
22278       DMask[DOffset + 1] = DOffset + 0;
22279       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22280       V = DAG.getBitcast(DVT, V);
22281       DCI.AddToWorklist(V.getNode());
22282       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22283                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22284       DCI.AddToWorklist(V.getNode());
22285       return DAG.getBitcast(VT, V);
22286     }
22287
22288     // Look for shuffle patterns which can be implemented as a single unpack.
22289     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22290     // only works when we have a PSHUFD followed by two half-shuffles.
22291     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22292         (V.getOpcode() == X86ISD::PSHUFLW ||
22293          V.getOpcode() == X86ISD::PSHUFHW) &&
22294         V.getOpcode() != N.getOpcode() &&
22295         V.hasOneUse()) {
22296       SDValue D = V.getOperand(0);
22297       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22298         D = D.getOperand(0);
22299       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22300         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22301         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22302         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22303         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22304         int WordMask[8];
22305         for (int i = 0; i < 4; ++i) {
22306           WordMask[i + NOffset] = Mask[i] + NOffset;
22307           WordMask[i + VOffset] = VMask[i] + VOffset;
22308         }
22309         // Map the word mask through the DWord mask.
22310         int MappedMask[8];
22311         for (int i = 0; i < 8; ++i)
22312           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22313         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22314             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22315           // We can replace all three shuffles with an unpack.
22316           V = DAG.getBitcast(VT, D.getOperand(0));
22317           DCI.AddToWorklist(V.getNode());
22318           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22319                                                 : X86ISD::UNPCKH,
22320                              DL, VT, V, V);
22321         }
22322       }
22323     }
22324
22325     break;
22326
22327   case X86ISD::PSHUFD:
22328     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22329       return NewN;
22330
22331     break;
22332   }
22333
22334   return SDValue();
22335 }
22336
22337 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22338 ///
22339 /// We combine this directly on the abstract vector shuffle nodes so it is
22340 /// easier to generically match. We also insert dummy vector shuffle nodes for
22341 /// the operands which explicitly discard the lanes which are unused by this
22342 /// operation to try to flow through the rest of the combiner the fact that
22343 /// they're unused.
22344 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22345   SDLoc DL(N);
22346   EVT VT = N->getValueType(0);
22347
22348   // We only handle target-independent shuffles.
22349   // FIXME: It would be easy and harmless to use the target shuffle mask
22350   // extraction tool to support more.
22351   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22352     return SDValue();
22353
22354   auto *SVN = cast<ShuffleVectorSDNode>(N);
22355   ArrayRef<int> Mask = SVN->getMask();
22356   SDValue V1 = N->getOperand(0);
22357   SDValue V2 = N->getOperand(1);
22358
22359   // We require the first shuffle operand to be the SUB node, and the second to
22360   // be the ADD node.
22361   // FIXME: We should support the commuted patterns.
22362   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22363     return SDValue();
22364
22365   // If there are other uses of these operations we can't fold them.
22366   if (!V1->hasOneUse() || !V2->hasOneUse())
22367     return SDValue();
22368
22369   // Ensure that both operations have the same operands. Note that we can
22370   // commute the FADD operands.
22371   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22372   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22373       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22374     return SDValue();
22375
22376   // We're looking for blends between FADD and FSUB nodes. We insist on these
22377   // nodes being lined up in a specific expected pattern.
22378   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22379         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22380         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22381     return SDValue();
22382
22383   // Only specific types are legal at this point, assert so we notice if and
22384   // when these change.
22385   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22386           VT == MVT::v4f64) &&
22387          "Unknown vector type encountered!");
22388
22389   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22390 }
22391
22392 /// PerformShuffleCombine - Performs several different shuffle combines.
22393 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22394                                      TargetLowering::DAGCombinerInfo &DCI,
22395                                      const X86Subtarget *Subtarget) {
22396   SDLoc dl(N);
22397   SDValue N0 = N->getOperand(0);
22398   SDValue N1 = N->getOperand(1);
22399   EVT VT = N->getValueType(0);
22400
22401   // Don't create instructions with illegal types after legalize types has run.
22402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22403   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22404     return SDValue();
22405
22406   // If we have legalized the vector types, look for blends of FADD and FSUB
22407   // nodes that we can fuse into an ADDSUB node.
22408   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22409     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22410       return AddSub;
22411
22412   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22413   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22414       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22415     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22416
22417   // During Type Legalization, when promoting illegal vector types,
22418   // the backend might introduce new shuffle dag nodes and bitcasts.
22419   //
22420   // This code performs the following transformation:
22421   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22422   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22423   //
22424   // We do this only if both the bitcast and the BINOP dag nodes have
22425   // one use. Also, perform this transformation only if the new binary
22426   // operation is legal. This is to avoid introducing dag nodes that
22427   // potentially need to be further expanded (or custom lowered) into a
22428   // less optimal sequence of dag nodes.
22429   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22430       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22431       N0.getOpcode() == ISD::BITCAST) {
22432     SDValue BC0 = N0.getOperand(0);
22433     EVT SVT = BC0.getValueType();
22434     unsigned Opcode = BC0.getOpcode();
22435     unsigned NumElts = VT.getVectorNumElements();
22436
22437     if (BC0.hasOneUse() && SVT.isVector() &&
22438         SVT.getVectorNumElements() * 2 == NumElts &&
22439         TLI.isOperationLegal(Opcode, VT)) {
22440       bool CanFold = false;
22441       switch (Opcode) {
22442       default : break;
22443       case ISD::ADD :
22444       case ISD::FADD :
22445       case ISD::SUB :
22446       case ISD::FSUB :
22447       case ISD::MUL :
22448       case ISD::FMUL :
22449         CanFold = true;
22450       }
22451
22452       unsigned SVTNumElts = SVT.getVectorNumElements();
22453       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22454       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22455         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22456       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22457         CanFold = SVOp->getMaskElt(i) < 0;
22458
22459       if (CanFold) {
22460         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22461         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22462         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22463         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22464       }
22465     }
22466   }
22467
22468   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22469   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22470   // consecutive, non-overlapping, and in the right order.
22471   SmallVector<SDValue, 16> Elts;
22472   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22473     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22474
22475   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22476     return LD;
22477
22478   if (isTargetShuffle(N->getOpcode())) {
22479     SDValue Shuffle =
22480         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22481     if (Shuffle.getNode())
22482       return Shuffle;
22483
22484     // Try recursively combining arbitrary sequences of x86 shuffle
22485     // instructions into higher-order shuffles. We do this after combining
22486     // specific PSHUF instruction sequences into their minimal form so that we
22487     // can evaluate how many specialized shuffle instructions are involved in
22488     // a particular chain.
22489     SmallVector<int, 1> NonceMask; // Just a placeholder.
22490     NonceMask.push_back(0);
22491     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22492                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22493                                       DCI, Subtarget))
22494       return SDValue(); // This routine will use CombineTo to replace N.
22495   }
22496
22497   return SDValue();
22498 }
22499
22500 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22501 /// specific shuffle of a load can be folded into a single element load.
22502 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22503 /// shuffles have been custom lowered so we need to handle those here.
22504 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22505                                          TargetLowering::DAGCombinerInfo &DCI) {
22506   if (DCI.isBeforeLegalizeOps())
22507     return SDValue();
22508
22509   SDValue InVec = N->getOperand(0);
22510   SDValue EltNo = N->getOperand(1);
22511
22512   if (!isa<ConstantSDNode>(EltNo))
22513     return SDValue();
22514
22515   EVT OriginalVT = InVec.getValueType();
22516
22517   if (InVec.getOpcode() == ISD::BITCAST) {
22518     // Don't duplicate a load with other uses.
22519     if (!InVec.hasOneUse())
22520       return SDValue();
22521     EVT BCVT = InVec.getOperand(0).getValueType();
22522     if (!BCVT.isVector() ||
22523         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22524       return SDValue();
22525     InVec = InVec.getOperand(0);
22526   }
22527
22528   EVT CurrentVT = InVec.getValueType();
22529
22530   if (!isTargetShuffle(InVec.getOpcode()))
22531     return SDValue();
22532
22533   // Don't duplicate a load with other uses.
22534   if (!InVec.hasOneUse())
22535     return SDValue();
22536
22537   SmallVector<int, 16> ShuffleMask;
22538   bool UnaryShuffle;
22539   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22540                             ShuffleMask, UnaryShuffle))
22541     return SDValue();
22542
22543   // Select the input vector, guarding against out of range extract vector.
22544   unsigned NumElems = CurrentVT.getVectorNumElements();
22545   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22546   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22547   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22548                                          : InVec.getOperand(1);
22549
22550   // If inputs to shuffle are the same for both ops, then allow 2 uses
22551   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22552                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22553
22554   if (LdNode.getOpcode() == ISD::BITCAST) {
22555     // Don't duplicate a load with other uses.
22556     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22557       return SDValue();
22558
22559     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22560     LdNode = LdNode.getOperand(0);
22561   }
22562
22563   if (!ISD::isNormalLoad(LdNode.getNode()))
22564     return SDValue();
22565
22566   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22567
22568   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22569     return SDValue();
22570
22571   EVT EltVT = N->getValueType(0);
22572   // If there's a bitcast before the shuffle, check if the load type and
22573   // alignment is valid.
22574   unsigned Align = LN0->getAlignment();
22575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22576   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22577       EltVT.getTypeForEVT(*DAG.getContext()));
22578
22579   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22580     return SDValue();
22581
22582   // All checks match so transform back to vector_shuffle so that DAG combiner
22583   // can finish the job
22584   SDLoc dl(N);
22585
22586   // Create shuffle node taking into account the case that its a unary shuffle
22587   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22588                                    : InVec.getOperand(1);
22589   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22590                                  InVec.getOperand(0), Shuffle,
22591                                  &ShuffleMask[0]);
22592   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22593   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22594                      EltNo);
22595 }
22596
22597 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22598 /// special and don't usually play with other vector types, it's better to
22599 /// handle them early to be sure we emit efficient code by avoiding
22600 /// store-load conversions.
22601 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22602   if (N->getValueType(0) != MVT::x86mmx ||
22603       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22604       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22605     return SDValue();
22606
22607   SDValue V = N->getOperand(0);
22608   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22609   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22610     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22611                        N->getValueType(0), V.getOperand(0));
22612
22613   return SDValue();
22614 }
22615
22616 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22617 /// generation and convert it from being a bunch of shuffles and extracts
22618 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22619 /// storing the value and loading scalars back, while for x64 we should
22620 /// use 64-bit extracts and shifts.
22621 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22622                                          TargetLowering::DAGCombinerInfo &DCI) {
22623   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22624     return NewOp;
22625
22626   SDValue InputVector = N->getOperand(0);
22627   SDLoc dl(InputVector);
22628   // Detect mmx to i32 conversion through a v2i32 elt extract.
22629   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22630       N->getValueType(0) == MVT::i32 &&
22631       InputVector.getValueType() == MVT::v2i32) {
22632
22633     // The bitcast source is a direct mmx result.
22634     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22635     if (MMXSrc.getValueType() == MVT::x86mmx)
22636       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22637                          N->getValueType(0),
22638                          InputVector.getNode()->getOperand(0));
22639
22640     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22641     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22642     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22643         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22644         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22645         MMXSrcOp.getValueType() == MVT::v1i64 &&
22646         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22647       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22648                          N->getValueType(0),
22649                          MMXSrcOp.getOperand(0));
22650   }
22651
22652   EVT VT = N->getValueType(0);
22653
22654   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22655       InputVector.getOpcode() == ISD::BITCAST &&
22656       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22657     uint64_t ExtractedElt =
22658           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22659     uint64_t InputValue =
22660           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22661     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22662     return DAG.getConstant(Res, dl, MVT::i1);
22663   }
22664   // Only operate on vectors of 4 elements, where the alternative shuffling
22665   // gets to be more expensive.
22666   if (InputVector.getValueType() != MVT::v4i32)
22667     return SDValue();
22668
22669   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22670   // single use which is a sign-extend or zero-extend, and all elements are
22671   // used.
22672   SmallVector<SDNode *, 4> Uses;
22673   unsigned ExtractedElements = 0;
22674   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22675        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22676     if (UI.getUse().getResNo() != InputVector.getResNo())
22677       return SDValue();
22678
22679     SDNode *Extract = *UI;
22680     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22681       return SDValue();
22682
22683     if (Extract->getValueType(0) != MVT::i32)
22684       return SDValue();
22685     if (!Extract->hasOneUse())
22686       return SDValue();
22687     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22688         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22689       return SDValue();
22690     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22691       return SDValue();
22692
22693     // Record which element was extracted.
22694     ExtractedElements |=
22695       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22696
22697     Uses.push_back(Extract);
22698   }
22699
22700   // If not all the elements were used, this may not be worthwhile.
22701   if (ExtractedElements != 15)
22702     return SDValue();
22703
22704   // Ok, we've now decided to do the transformation.
22705   // If 64-bit shifts are legal, use the extract-shift sequence,
22706   // otherwise bounce the vector off the cache.
22707   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22708   SDValue Vals[4];
22709
22710   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22711     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22712     auto &DL = DAG.getDataLayout();
22713     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22714     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22715       DAG.getConstant(0, dl, VecIdxTy));
22716     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22717       DAG.getConstant(1, dl, VecIdxTy));
22718
22719     SDValue ShAmt = DAG.getConstant(
22720         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22721     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22722     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22723       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22724     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22725     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22726       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22727   } else {
22728     // Store the value to a temporary stack slot.
22729     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22730     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22731       MachinePointerInfo(), false, false, 0);
22732
22733     EVT ElementType = InputVector.getValueType().getVectorElementType();
22734     unsigned EltSize = ElementType.getSizeInBits() / 8;
22735
22736     // Replace each use (extract) with a load of the appropriate element.
22737     for (unsigned i = 0; i < 4; ++i) {
22738       uint64_t Offset = EltSize * i;
22739       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22740       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22741
22742       SDValue ScalarAddr =
22743           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22744
22745       // Load the scalar.
22746       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22747                             ScalarAddr, MachinePointerInfo(),
22748                             false, false, false, 0);
22749
22750     }
22751   }
22752
22753   // Replace the extracts
22754   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22755     UE = Uses.end(); UI != UE; ++UI) {
22756     SDNode *Extract = *UI;
22757
22758     SDValue Idx = Extract->getOperand(1);
22759     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22760     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22761   }
22762
22763   // The replacement was made in place; don't return anything.
22764   return SDValue();
22765 }
22766
22767 static SDValue
22768 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22769                                       const X86Subtarget *Subtarget) {
22770   SDLoc dl(N);
22771   SDValue Cond = N->getOperand(0);
22772   SDValue LHS = N->getOperand(1);
22773   SDValue RHS = N->getOperand(2);
22774
22775   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22776     SDValue CondSrc = Cond->getOperand(0);
22777     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22778       Cond = CondSrc->getOperand(0);
22779   }
22780
22781   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22782     return SDValue();
22783
22784   // A vselect where all conditions and data are constants can be optimized into
22785   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22786   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22787       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22788     return SDValue();
22789
22790   unsigned MaskValue = 0;
22791   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22792     return SDValue();
22793
22794   MVT VT = N->getSimpleValueType(0);
22795   unsigned NumElems = VT.getVectorNumElements();
22796   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22797   for (unsigned i = 0; i < NumElems; ++i) {
22798     // Be sure we emit undef where we can.
22799     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22800       ShuffleMask[i] = -1;
22801     else
22802       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22803   }
22804
22805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22806   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22807     return SDValue();
22808   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22809 }
22810
22811 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22812 /// nodes.
22813 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22814                                     TargetLowering::DAGCombinerInfo &DCI,
22815                                     const X86Subtarget *Subtarget) {
22816   SDLoc DL(N);
22817   SDValue Cond = N->getOperand(0);
22818   // Get the LHS/RHS of the select.
22819   SDValue LHS = N->getOperand(1);
22820   SDValue RHS = N->getOperand(2);
22821   EVT VT = LHS.getValueType();
22822   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22823
22824   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22825   // instructions match the semantics of the common C idiom x<y?x:y but not
22826   // x<=y?x:y, because of how they handle negative zero (which can be
22827   // ignored in unsafe-math mode).
22828   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22829   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22830       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22831       (Subtarget->hasSSE2() ||
22832        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22833     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22834
22835     unsigned Opcode = 0;
22836     // Check for x CC y ? x : y.
22837     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22838         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22839       switch (CC) {
22840       default: break;
22841       case ISD::SETULT:
22842         // Converting this to a min would handle NaNs incorrectly, and swapping
22843         // the operands would cause it to handle comparisons between positive
22844         // and negative zero incorrectly.
22845         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22846           if (!DAG.getTarget().Options.UnsafeFPMath &&
22847               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22848             break;
22849           std::swap(LHS, RHS);
22850         }
22851         Opcode = X86ISD::FMIN;
22852         break;
22853       case ISD::SETOLE:
22854         // Converting this to a min would handle comparisons between positive
22855         // and negative zero incorrectly.
22856         if (!DAG.getTarget().Options.UnsafeFPMath &&
22857             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22858           break;
22859         Opcode = X86ISD::FMIN;
22860         break;
22861       case ISD::SETULE:
22862         // Converting this to a min would handle both negative zeros and NaNs
22863         // incorrectly, but we can swap the operands to fix both.
22864         std::swap(LHS, RHS);
22865       case ISD::SETOLT:
22866       case ISD::SETLT:
22867       case ISD::SETLE:
22868         Opcode = X86ISD::FMIN;
22869         break;
22870
22871       case ISD::SETOGE:
22872         // Converting this to a max would handle comparisons between positive
22873         // and negative zero incorrectly.
22874         if (!DAG.getTarget().Options.UnsafeFPMath &&
22875             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22876           break;
22877         Opcode = X86ISD::FMAX;
22878         break;
22879       case ISD::SETUGT:
22880         // Converting this to a max would handle NaNs incorrectly, and swapping
22881         // the operands would cause it to handle comparisons between positive
22882         // and negative zero incorrectly.
22883         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22884           if (!DAG.getTarget().Options.UnsafeFPMath &&
22885               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22886             break;
22887           std::swap(LHS, RHS);
22888         }
22889         Opcode = X86ISD::FMAX;
22890         break;
22891       case ISD::SETUGE:
22892         // Converting this to a max would handle both negative zeros and NaNs
22893         // incorrectly, but we can swap the operands to fix both.
22894         std::swap(LHS, RHS);
22895       case ISD::SETOGT:
22896       case ISD::SETGT:
22897       case ISD::SETGE:
22898         Opcode = X86ISD::FMAX;
22899         break;
22900       }
22901     // Check for x CC y ? y : x -- a min/max with reversed arms.
22902     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22903                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22904       switch (CC) {
22905       default: break;
22906       case ISD::SETOGE:
22907         // Converting this to a min would handle comparisons between positive
22908         // and negative zero incorrectly, and swapping the operands would
22909         // cause it to handle NaNs incorrectly.
22910         if (!DAG.getTarget().Options.UnsafeFPMath &&
22911             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22912           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22913             break;
22914           std::swap(LHS, RHS);
22915         }
22916         Opcode = X86ISD::FMIN;
22917         break;
22918       case ISD::SETUGT:
22919         // Converting this to a min would handle NaNs incorrectly.
22920         if (!DAG.getTarget().Options.UnsafeFPMath &&
22921             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22922           break;
22923         Opcode = X86ISD::FMIN;
22924         break;
22925       case ISD::SETUGE:
22926         // Converting this to a min would handle both negative zeros and NaNs
22927         // incorrectly, but we can swap the operands to fix both.
22928         std::swap(LHS, RHS);
22929       case ISD::SETOGT:
22930       case ISD::SETGT:
22931       case ISD::SETGE:
22932         Opcode = X86ISD::FMIN;
22933         break;
22934
22935       case ISD::SETULT:
22936         // Converting this to a max would handle NaNs incorrectly.
22937         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22938           break;
22939         Opcode = X86ISD::FMAX;
22940         break;
22941       case ISD::SETOLE:
22942         // Converting this to a max would handle comparisons between positive
22943         // and negative zero incorrectly, and swapping the operands would
22944         // cause it to handle NaNs incorrectly.
22945         if (!DAG.getTarget().Options.UnsafeFPMath &&
22946             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22947           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22948             break;
22949           std::swap(LHS, RHS);
22950         }
22951         Opcode = X86ISD::FMAX;
22952         break;
22953       case ISD::SETULE:
22954         // Converting this to a max would handle both negative zeros and NaNs
22955         // incorrectly, but we can swap the operands to fix both.
22956         std::swap(LHS, RHS);
22957       case ISD::SETOLT:
22958       case ISD::SETLT:
22959       case ISD::SETLE:
22960         Opcode = X86ISD::FMAX;
22961         break;
22962       }
22963     }
22964
22965     if (Opcode)
22966       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22967   }
22968
22969   EVT CondVT = Cond.getValueType();
22970   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22971       CondVT.getVectorElementType() == MVT::i1) {
22972     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22973     // lowering on KNL. In this case we convert it to
22974     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22975     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22976     // Since SKX these selects have a proper lowering.
22977     EVT OpVT = LHS.getValueType();
22978     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22979         (OpVT.getVectorElementType() == MVT::i8 ||
22980          OpVT.getVectorElementType() == MVT::i16) &&
22981         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22982       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22983       DCI.AddToWorklist(Cond.getNode());
22984       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22985     }
22986   }
22987   // If this is a select between two integer constants, try to do some
22988   // optimizations.
22989   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22990     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22991       // Don't do this for crazy integer types.
22992       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22993         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22994         // so that TrueC (the true value) is larger than FalseC.
22995         bool NeedsCondInvert = false;
22996
22997         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22998             // Efficiently invertible.
22999             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23000              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23001               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23002           NeedsCondInvert = true;
23003           std::swap(TrueC, FalseC);
23004         }
23005
23006         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23007         if (FalseC->getAPIntValue() == 0 &&
23008             TrueC->getAPIntValue().isPowerOf2()) {
23009           if (NeedsCondInvert) // Invert the condition if needed.
23010             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23011                                DAG.getConstant(1, DL, Cond.getValueType()));
23012
23013           // Zero extend the condition if needed.
23014           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23015
23016           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23017           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23018                              DAG.getConstant(ShAmt, DL, MVT::i8));
23019         }
23020
23021         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23022         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23023           if (NeedsCondInvert) // Invert the condition if needed.
23024             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23025                                DAG.getConstant(1, DL, Cond.getValueType()));
23026
23027           // Zero extend the condition if needed.
23028           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23029                              FalseC->getValueType(0), Cond);
23030           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23031                              SDValue(FalseC, 0));
23032         }
23033
23034         // Optimize cases that will turn into an LEA instruction.  This requires
23035         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23036         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23037           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23038           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23039
23040           bool isFastMultiplier = false;
23041           if (Diff < 10) {
23042             switch ((unsigned char)Diff) {
23043               default: break;
23044               case 1:  // result = add base, cond
23045               case 2:  // result = lea base(    , cond*2)
23046               case 3:  // result = lea base(cond, cond*2)
23047               case 4:  // result = lea base(    , cond*4)
23048               case 5:  // result = lea base(cond, cond*4)
23049               case 8:  // result = lea base(    , cond*8)
23050               case 9:  // result = lea base(cond, cond*8)
23051                 isFastMultiplier = true;
23052                 break;
23053             }
23054           }
23055
23056           if (isFastMultiplier) {
23057             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23058             if (NeedsCondInvert) // Invert the condition if needed.
23059               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23060                                  DAG.getConstant(1, DL, Cond.getValueType()));
23061
23062             // Zero extend the condition if needed.
23063             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23064                                Cond);
23065             // Scale the condition by the difference.
23066             if (Diff != 1)
23067               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23068                                  DAG.getConstant(Diff, DL,
23069                                                  Cond.getValueType()));
23070
23071             // Add the base if non-zero.
23072             if (FalseC->getAPIntValue() != 0)
23073               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23074                                  SDValue(FalseC, 0));
23075             return Cond;
23076           }
23077         }
23078       }
23079   }
23080
23081   // Canonicalize max and min:
23082   // (x > y) ? x : y -> (x >= y) ? x : y
23083   // (x < y) ? x : y -> (x <= y) ? x : y
23084   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23085   // the need for an extra compare
23086   // against zero. e.g.
23087   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23088   // subl   %esi, %edi
23089   // testl  %edi, %edi
23090   // movl   $0, %eax
23091   // cmovgl %edi, %eax
23092   // =>
23093   // xorl   %eax, %eax
23094   // subl   %esi, $edi
23095   // cmovsl %eax, %edi
23096   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23097       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23098       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23099     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23100     switch (CC) {
23101     default: break;
23102     case ISD::SETLT:
23103     case ISD::SETGT: {
23104       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23105       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23106                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23107       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23108     }
23109     }
23110   }
23111
23112   // Early exit check
23113   if (!TLI.isTypeLegal(VT))
23114     return SDValue();
23115
23116   // Match VSELECTs into subs with unsigned saturation.
23117   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23118       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23119       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23120        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23121     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23122
23123     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23124     // left side invert the predicate to simplify logic below.
23125     SDValue Other;
23126     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23127       Other = RHS;
23128       CC = ISD::getSetCCInverse(CC, true);
23129     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23130       Other = LHS;
23131     }
23132
23133     if (Other.getNode() && Other->getNumOperands() == 2 &&
23134         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23135       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23136       SDValue CondRHS = Cond->getOperand(1);
23137
23138       // Look for a general sub with unsigned saturation first.
23139       // x >= y ? x-y : 0 --> subus x, y
23140       // x >  y ? x-y : 0 --> subus x, y
23141       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23142           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23143         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23144
23145       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23146         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23147           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23148             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23149               // If the RHS is a constant we have to reverse the const
23150               // canonicalization.
23151               // x > C-1 ? x+-C : 0 --> subus x, C
23152               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23153                   CondRHSConst->getAPIntValue() ==
23154                       (-OpRHSConst->getAPIntValue() - 1))
23155                 return DAG.getNode(
23156                     X86ISD::SUBUS, DL, VT, OpLHS,
23157                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23158
23159           // Another special case: If C was a sign bit, the sub has been
23160           // canonicalized into a xor.
23161           // FIXME: Would it be better to use computeKnownBits to determine
23162           //        whether it's safe to decanonicalize the xor?
23163           // x s< 0 ? x^C : 0 --> subus x, C
23164           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23165               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23166               OpRHSConst->getAPIntValue().isSignBit())
23167             // Note that we have to rebuild the RHS constant here to ensure we
23168             // don't rely on particular values of undef lanes.
23169             return DAG.getNode(
23170                 X86ISD::SUBUS, DL, VT, OpLHS,
23171                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23172         }
23173     }
23174   }
23175
23176   // Simplify vector selection if condition value type matches vselect
23177   // operand type
23178   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23179     assert(Cond.getValueType().isVector() &&
23180            "vector select expects a vector selector!");
23181
23182     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23183     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23184
23185     // Try invert the condition if true value is not all 1s and false value
23186     // is not all 0s.
23187     if (!TValIsAllOnes && !FValIsAllZeros &&
23188         // Check if the selector will be produced by CMPP*/PCMP*
23189         Cond.getOpcode() == ISD::SETCC &&
23190         // Check if SETCC has already been promoted
23191         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23192             CondVT) {
23193       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23194       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23195
23196       if (TValIsAllZeros || FValIsAllOnes) {
23197         SDValue CC = Cond.getOperand(2);
23198         ISD::CondCode NewCC =
23199           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23200                                Cond.getOperand(0).getValueType().isInteger());
23201         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23202         std::swap(LHS, RHS);
23203         TValIsAllOnes = FValIsAllOnes;
23204         FValIsAllZeros = TValIsAllZeros;
23205       }
23206     }
23207
23208     if (TValIsAllOnes || FValIsAllZeros) {
23209       SDValue Ret;
23210
23211       if (TValIsAllOnes && FValIsAllZeros)
23212         Ret = Cond;
23213       else if (TValIsAllOnes)
23214         Ret =
23215             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23216       else if (FValIsAllZeros)
23217         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23218                           DAG.getBitcast(CondVT, LHS));
23219
23220       return DAG.getBitcast(VT, Ret);
23221     }
23222   }
23223
23224   // We should generate an X86ISD::BLENDI from a vselect if its argument
23225   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23226   // constants. This specific pattern gets generated when we split a
23227   // selector for a 512 bit vector in a machine without AVX512 (but with
23228   // 256-bit vectors), during legalization:
23229   //
23230   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23231   //
23232   // Iff we find this pattern and the build_vectors are built from
23233   // constants, we translate the vselect into a shuffle_vector that we
23234   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23235   if ((N->getOpcode() == ISD::VSELECT ||
23236        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23237       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23238     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23239     if (Shuffle.getNode())
23240       return Shuffle;
23241   }
23242
23243   // If this is a *dynamic* select (non-constant condition) and we can match
23244   // this node with one of the variable blend instructions, restructure the
23245   // condition so that the blends can use the high bit of each element and use
23246   // SimplifyDemandedBits to simplify the condition operand.
23247   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23248       !DCI.isBeforeLegalize() &&
23249       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23250     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23251
23252     // Don't optimize vector selects that map to mask-registers.
23253     if (BitWidth == 1)
23254       return SDValue();
23255
23256     // We can only handle the cases where VSELECT is directly legal on the
23257     // subtarget. We custom lower VSELECT nodes with constant conditions and
23258     // this makes it hard to see whether a dynamic VSELECT will correctly
23259     // lower, so we both check the operation's status and explicitly handle the
23260     // cases where a *dynamic* blend will fail even though a constant-condition
23261     // blend could be custom lowered.
23262     // FIXME: We should find a better way to handle this class of problems.
23263     // Potentially, we should combine constant-condition vselect nodes
23264     // pre-legalization into shuffles and not mark as many types as custom
23265     // lowered.
23266     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23267       return SDValue();
23268     // FIXME: We don't support i16-element blends currently. We could and
23269     // should support them by making *all* the bits in the condition be set
23270     // rather than just the high bit and using an i8-element blend.
23271     if (VT.getScalarType() == MVT::i16)
23272       return SDValue();
23273     // Dynamic blending was only available from SSE4.1 onward.
23274     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23275       return SDValue();
23276     // Byte blends are only available in AVX2
23277     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23278         !Subtarget->hasAVX2())
23279       return SDValue();
23280
23281     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23282     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23283
23284     APInt KnownZero, KnownOne;
23285     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23286                                           DCI.isBeforeLegalizeOps());
23287     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23288         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23289                                  TLO)) {
23290       // If we changed the computation somewhere in the DAG, this change
23291       // will affect all users of Cond.
23292       // Make sure it is fine and update all the nodes so that we do not
23293       // use the generic VSELECT anymore. Otherwise, we may perform
23294       // wrong optimizations as we messed up with the actual expectation
23295       // for the vector boolean values.
23296       if (Cond != TLO.Old) {
23297         // Check all uses of that condition operand to check whether it will be
23298         // consumed by non-BLEND instructions, which may depend on all bits are
23299         // set properly.
23300         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23301              I != E; ++I)
23302           if (I->getOpcode() != ISD::VSELECT)
23303             // TODO: Add other opcodes eventually lowered into BLEND.
23304             return SDValue();
23305
23306         // Update all the users of the condition, before committing the change,
23307         // so that the VSELECT optimizations that expect the correct vector
23308         // boolean value will not be triggered.
23309         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23310              I != E; ++I)
23311           DAG.ReplaceAllUsesOfValueWith(
23312               SDValue(*I, 0),
23313               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23314                           Cond, I->getOperand(1), I->getOperand(2)));
23315         DCI.CommitTargetLoweringOpt(TLO);
23316         return SDValue();
23317       }
23318       // At this point, only Cond is changed. Change the condition
23319       // just for N to keep the opportunity to optimize all other
23320       // users their own way.
23321       DAG.ReplaceAllUsesOfValueWith(
23322           SDValue(N, 0),
23323           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23324                       TLO.New, N->getOperand(1), N->getOperand(2)));
23325       return SDValue();
23326     }
23327   }
23328
23329   return SDValue();
23330 }
23331
23332 // Check whether a boolean test is testing a boolean value generated by
23333 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23334 // code.
23335 //
23336 // Simplify the following patterns:
23337 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23338 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23339 // to (Op EFLAGS Cond)
23340 //
23341 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23342 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23343 // to (Op EFLAGS !Cond)
23344 //
23345 // where Op could be BRCOND or CMOV.
23346 //
23347 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23348   // Quit if not CMP and SUB with its value result used.
23349   if (Cmp.getOpcode() != X86ISD::CMP &&
23350       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23351       return SDValue();
23352
23353   // Quit if not used as a boolean value.
23354   if (CC != X86::COND_E && CC != X86::COND_NE)
23355     return SDValue();
23356
23357   // Check CMP operands. One of them should be 0 or 1 and the other should be
23358   // an SetCC or extended from it.
23359   SDValue Op1 = Cmp.getOperand(0);
23360   SDValue Op2 = Cmp.getOperand(1);
23361
23362   SDValue SetCC;
23363   const ConstantSDNode* C = nullptr;
23364   bool needOppositeCond = (CC == X86::COND_E);
23365   bool checkAgainstTrue = false; // Is it a comparison against 1?
23366
23367   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23368     SetCC = Op2;
23369   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23370     SetCC = Op1;
23371   else // Quit if all operands are not constants.
23372     return SDValue();
23373
23374   if (C->getZExtValue() == 1) {
23375     needOppositeCond = !needOppositeCond;
23376     checkAgainstTrue = true;
23377   } else if (C->getZExtValue() != 0)
23378     // Quit if the constant is neither 0 or 1.
23379     return SDValue();
23380
23381   bool truncatedToBoolWithAnd = false;
23382   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23383   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23384          SetCC.getOpcode() == ISD::TRUNCATE ||
23385          SetCC.getOpcode() == ISD::AND) {
23386     if (SetCC.getOpcode() == ISD::AND) {
23387       int OpIdx = -1;
23388       ConstantSDNode *CS;
23389       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23390           CS->getZExtValue() == 1)
23391         OpIdx = 1;
23392       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23393           CS->getZExtValue() == 1)
23394         OpIdx = 0;
23395       if (OpIdx == -1)
23396         break;
23397       SetCC = SetCC.getOperand(OpIdx);
23398       truncatedToBoolWithAnd = true;
23399     } else
23400       SetCC = SetCC.getOperand(0);
23401   }
23402
23403   switch (SetCC.getOpcode()) {
23404   case X86ISD::SETCC_CARRY:
23405     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23406     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23407     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23408     // truncated to i1 using 'and'.
23409     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23410       break;
23411     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23412            "Invalid use of SETCC_CARRY!");
23413     // FALL THROUGH
23414   case X86ISD::SETCC:
23415     // Set the condition code or opposite one if necessary.
23416     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23417     if (needOppositeCond)
23418       CC = X86::GetOppositeBranchCondition(CC);
23419     return SetCC.getOperand(1);
23420   case X86ISD::CMOV: {
23421     // Check whether false/true value has canonical one, i.e. 0 or 1.
23422     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23423     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23424     // Quit if true value is not a constant.
23425     if (!TVal)
23426       return SDValue();
23427     // Quit if false value is not a constant.
23428     if (!FVal) {
23429       SDValue Op = SetCC.getOperand(0);
23430       // Skip 'zext' or 'trunc' node.
23431       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23432           Op.getOpcode() == ISD::TRUNCATE)
23433         Op = Op.getOperand(0);
23434       // A special case for rdrand/rdseed, where 0 is set if false cond is
23435       // found.
23436       if ((Op.getOpcode() != X86ISD::RDRAND &&
23437            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23438         return SDValue();
23439     }
23440     // Quit if false value is not the constant 0 or 1.
23441     bool FValIsFalse = true;
23442     if (FVal && FVal->getZExtValue() != 0) {
23443       if (FVal->getZExtValue() != 1)
23444         return SDValue();
23445       // If FVal is 1, opposite cond is needed.
23446       needOppositeCond = !needOppositeCond;
23447       FValIsFalse = false;
23448     }
23449     // Quit if TVal is not the constant opposite of FVal.
23450     if (FValIsFalse && TVal->getZExtValue() != 1)
23451       return SDValue();
23452     if (!FValIsFalse && TVal->getZExtValue() != 0)
23453       return SDValue();
23454     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23455     if (needOppositeCond)
23456       CC = X86::GetOppositeBranchCondition(CC);
23457     return SetCC.getOperand(3);
23458   }
23459   }
23460
23461   return SDValue();
23462 }
23463
23464 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23465 /// Match:
23466 ///   (X86or (X86setcc) (X86setcc))
23467 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23468 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23469                                            X86::CondCode &CC1, SDValue &Flags,
23470                                            bool &isAnd) {
23471   if (Cond->getOpcode() == X86ISD::CMP) {
23472     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23473     if (!CondOp1C || !CondOp1C->isNullValue())
23474       return false;
23475
23476     Cond = Cond->getOperand(0);
23477   }
23478
23479   isAnd = false;
23480
23481   SDValue SetCC0, SetCC1;
23482   switch (Cond->getOpcode()) {
23483   default: return false;
23484   case ISD::AND:
23485   case X86ISD::AND:
23486     isAnd = true;
23487     // fallthru
23488   case ISD::OR:
23489   case X86ISD::OR:
23490     SetCC0 = Cond->getOperand(0);
23491     SetCC1 = Cond->getOperand(1);
23492     break;
23493   };
23494
23495   // Make sure we have SETCC nodes, using the same flags value.
23496   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23497       SetCC1.getOpcode() != X86ISD::SETCC ||
23498       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23499     return false;
23500
23501   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23502   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23503   Flags = SetCC0->getOperand(1);
23504   return true;
23505 }
23506
23507 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23508 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23509                                   TargetLowering::DAGCombinerInfo &DCI,
23510                                   const X86Subtarget *Subtarget) {
23511   SDLoc DL(N);
23512
23513   // If the flag operand isn't dead, don't touch this CMOV.
23514   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23515     return SDValue();
23516
23517   SDValue FalseOp = N->getOperand(0);
23518   SDValue TrueOp = N->getOperand(1);
23519   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23520   SDValue Cond = N->getOperand(3);
23521
23522   if (CC == X86::COND_E || CC == X86::COND_NE) {
23523     switch (Cond.getOpcode()) {
23524     default: break;
23525     case X86ISD::BSR:
23526     case X86ISD::BSF:
23527       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23528       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23529         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23530     }
23531   }
23532
23533   SDValue Flags;
23534
23535   Flags = checkBoolTestSetCCCombine(Cond, CC);
23536   if (Flags.getNode() &&
23537       // Extra check as FCMOV only supports a subset of X86 cond.
23538       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23539     SDValue Ops[] = { FalseOp, TrueOp,
23540                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23541     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23542   }
23543
23544   // If this is a select between two integer constants, try to do some
23545   // optimizations.  Note that the operands are ordered the opposite of SELECT
23546   // operands.
23547   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23548     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23549       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23550       // larger than FalseC (the false value).
23551       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23552         CC = X86::GetOppositeBranchCondition(CC);
23553         std::swap(TrueC, FalseC);
23554         std::swap(TrueOp, FalseOp);
23555       }
23556
23557       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23558       // This is efficient for any integer data type (including i8/i16) and
23559       // shift amount.
23560       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23561         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23562                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23563
23564         // Zero extend the condition if needed.
23565         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23566
23567         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23568         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23569                            DAG.getConstant(ShAmt, DL, MVT::i8));
23570         if (N->getNumValues() == 2)  // Dead flag value?
23571           return DCI.CombineTo(N, Cond, SDValue());
23572         return Cond;
23573       }
23574
23575       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23576       // for any integer data type, including i8/i16.
23577       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23578         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23579                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23580
23581         // Zero extend the condition if needed.
23582         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23583                            FalseC->getValueType(0), Cond);
23584         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23585                            SDValue(FalseC, 0));
23586
23587         if (N->getNumValues() == 2)  // Dead flag value?
23588           return DCI.CombineTo(N, Cond, SDValue());
23589         return Cond;
23590       }
23591
23592       // Optimize cases that will turn into an LEA instruction.  This requires
23593       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23594       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23595         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23596         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23597
23598         bool isFastMultiplier = false;
23599         if (Diff < 10) {
23600           switch ((unsigned char)Diff) {
23601           default: break;
23602           case 1:  // result = add base, cond
23603           case 2:  // result = lea base(    , cond*2)
23604           case 3:  // result = lea base(cond, cond*2)
23605           case 4:  // result = lea base(    , cond*4)
23606           case 5:  // result = lea base(cond, cond*4)
23607           case 8:  // result = lea base(    , cond*8)
23608           case 9:  // result = lea base(cond, cond*8)
23609             isFastMultiplier = true;
23610             break;
23611           }
23612         }
23613
23614         if (isFastMultiplier) {
23615           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23616           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23617                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23618           // Zero extend the condition if needed.
23619           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23620                              Cond);
23621           // Scale the condition by the difference.
23622           if (Diff != 1)
23623             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23624                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23625
23626           // Add the base if non-zero.
23627           if (FalseC->getAPIntValue() != 0)
23628             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23629                                SDValue(FalseC, 0));
23630           if (N->getNumValues() == 2)  // Dead flag value?
23631             return DCI.CombineTo(N, Cond, SDValue());
23632           return Cond;
23633         }
23634       }
23635     }
23636   }
23637
23638   // Handle these cases:
23639   //   (select (x != c), e, c) -> select (x != c), e, x),
23640   //   (select (x == c), c, e) -> select (x == c), x, e)
23641   // where the c is an integer constant, and the "select" is the combination
23642   // of CMOV and CMP.
23643   //
23644   // The rationale for this change is that the conditional-move from a constant
23645   // needs two instructions, however, conditional-move from a register needs
23646   // only one instruction.
23647   //
23648   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23649   //  some instruction-combining opportunities. This opt needs to be
23650   //  postponed as late as possible.
23651   //
23652   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23653     // the DCI.xxxx conditions are provided to postpone the optimization as
23654     // late as possible.
23655
23656     ConstantSDNode *CmpAgainst = nullptr;
23657     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23658         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23659         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23660
23661       if (CC == X86::COND_NE &&
23662           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23663         CC = X86::GetOppositeBranchCondition(CC);
23664         std::swap(TrueOp, FalseOp);
23665       }
23666
23667       if (CC == X86::COND_E &&
23668           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23669         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23670                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23671         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23672       }
23673     }
23674   }
23675
23676   // Fold and/or of setcc's to double CMOV:
23677   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23678   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23679   //
23680   // This combine lets us generate:
23681   //   cmovcc1 (jcc1 if we don't have CMOV)
23682   //   cmovcc2 (same)
23683   // instead of:
23684   //   setcc1
23685   //   setcc2
23686   //   and/or
23687   //   cmovne (jne if we don't have CMOV)
23688   // When we can't use the CMOV instruction, it might increase branch
23689   // mispredicts.
23690   // When we can use CMOV, or when there is no mispredict, this improves
23691   // throughput and reduces register pressure.
23692   //
23693   if (CC == X86::COND_NE) {
23694     SDValue Flags;
23695     X86::CondCode CC0, CC1;
23696     bool isAndSetCC;
23697     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23698       if (isAndSetCC) {
23699         std::swap(FalseOp, TrueOp);
23700         CC0 = X86::GetOppositeBranchCondition(CC0);
23701         CC1 = X86::GetOppositeBranchCondition(CC1);
23702       }
23703
23704       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23705         Flags};
23706       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23707       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23708       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23709       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23710       return CMOV;
23711     }
23712   }
23713
23714   return SDValue();
23715 }
23716
23717 /// PerformMulCombine - Optimize a single multiply with constant into two
23718 /// in order to implement it with two cheaper instructions, e.g.
23719 /// LEA + SHL, LEA + LEA.
23720 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23721                                  TargetLowering::DAGCombinerInfo &DCI) {
23722   // An imul is usually smaller than the alternative sequence.
23723   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23724     return SDValue();
23725
23726   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23727     return SDValue();
23728
23729   EVT VT = N->getValueType(0);
23730   if (VT != MVT::i64 && VT != MVT::i32)
23731     return SDValue();
23732
23733   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23734   if (!C)
23735     return SDValue();
23736   uint64_t MulAmt = C->getZExtValue();
23737   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23738     return SDValue();
23739
23740   uint64_t MulAmt1 = 0;
23741   uint64_t MulAmt2 = 0;
23742   if ((MulAmt % 9) == 0) {
23743     MulAmt1 = 9;
23744     MulAmt2 = MulAmt / 9;
23745   } else if ((MulAmt % 5) == 0) {
23746     MulAmt1 = 5;
23747     MulAmt2 = MulAmt / 5;
23748   } else if ((MulAmt % 3) == 0) {
23749     MulAmt1 = 3;
23750     MulAmt2 = MulAmt / 3;
23751   }
23752   if (MulAmt2 &&
23753       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23754     SDLoc DL(N);
23755
23756     if (isPowerOf2_64(MulAmt2) &&
23757         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23758       // If second multiplifer is pow2, issue it first. We want the multiply by
23759       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23760       // is an add.
23761       std::swap(MulAmt1, MulAmt2);
23762
23763     SDValue NewMul;
23764     if (isPowerOf2_64(MulAmt1))
23765       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23766                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23767     else
23768       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23769                            DAG.getConstant(MulAmt1, DL, VT));
23770
23771     if (isPowerOf2_64(MulAmt2))
23772       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23773                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23774     else
23775       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23776                            DAG.getConstant(MulAmt2, DL, VT));
23777
23778     // Do not add new nodes to DAG combiner worklist.
23779     DCI.CombineTo(N, NewMul, false);
23780   }
23781   return SDValue();
23782 }
23783
23784 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23785   SDValue N0 = N->getOperand(0);
23786   SDValue N1 = N->getOperand(1);
23787   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23788   EVT VT = N0.getValueType();
23789
23790   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23791   // since the result of setcc_c is all zero's or all ones.
23792   if (VT.isInteger() && !VT.isVector() &&
23793       N1C && N0.getOpcode() == ISD::AND &&
23794       N0.getOperand(1).getOpcode() == ISD::Constant) {
23795     SDValue N00 = N0.getOperand(0);
23796     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23797     APInt ShAmt = N1C->getAPIntValue();
23798     Mask = Mask.shl(ShAmt);
23799     bool MaskOK = false;
23800     // We can handle cases concerning bit-widening nodes containing setcc_c if
23801     // we carefully interrogate the mask to make sure we are semantics
23802     // preserving.
23803     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23804     // of the underlying setcc_c operation if the setcc_c was zero extended.
23805     // Consider the following example:
23806     //   zext(setcc_c)                 -> i32 0x0000FFFF
23807     //   c1                            -> i32 0x0000FFFF
23808     //   c2                            -> i32 0x00000001
23809     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23810     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23811     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23812       MaskOK = true;
23813     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23814                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23815       MaskOK = true;
23816     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23817                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23818                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23819       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23820     }
23821     if (MaskOK && Mask != 0) {
23822       SDLoc DL(N);
23823       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23824     }
23825   }
23826
23827   // Hardware support for vector shifts is sparse which makes us scalarize the
23828   // vector operations in many cases. Also, on sandybridge ADD is faster than
23829   // shl.
23830   // (shl V, 1) -> add V,V
23831   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23832     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23833       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23834       // We shift all of the values by one. In many cases we do not have
23835       // hardware support for this operation. This is better expressed as an ADD
23836       // of two values.
23837       if (N1SplatC->getAPIntValue() == 1)
23838         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23839     }
23840
23841   return SDValue();
23842 }
23843
23844 /// \brief Returns a vector of 0s if the node in input is a vector logical
23845 /// shift by a constant amount which is known to be bigger than or equal
23846 /// to the vector element size in bits.
23847 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23848                                       const X86Subtarget *Subtarget) {
23849   EVT VT = N->getValueType(0);
23850
23851   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23852       (!Subtarget->hasInt256() ||
23853        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23854     return SDValue();
23855
23856   SDValue Amt = N->getOperand(1);
23857   SDLoc DL(N);
23858   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23859     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23860       APInt ShiftAmt = AmtSplat->getAPIntValue();
23861       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23862
23863       // SSE2/AVX2 logical shifts always return a vector of 0s
23864       // if the shift amount is bigger than or equal to
23865       // the element size. The constant shift amount will be
23866       // encoded as a 8-bit immediate.
23867       if (ShiftAmt.trunc(8).uge(MaxAmount))
23868         return getZeroVector(VT, Subtarget, DAG, DL);
23869     }
23870
23871   return SDValue();
23872 }
23873
23874 /// PerformShiftCombine - Combine shifts.
23875 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23876                                    TargetLowering::DAGCombinerInfo &DCI,
23877                                    const X86Subtarget *Subtarget) {
23878   if (N->getOpcode() == ISD::SHL)
23879     if (SDValue V = PerformSHLCombine(N, DAG))
23880       return V;
23881
23882   // Try to fold this logical shift into a zero vector.
23883   if (N->getOpcode() != ISD::SRA)
23884     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23885       return V;
23886
23887   return SDValue();
23888 }
23889
23890 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23891 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23892 // and friends.  Likewise for OR -> CMPNEQSS.
23893 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23894                             TargetLowering::DAGCombinerInfo &DCI,
23895                             const X86Subtarget *Subtarget) {
23896   unsigned opcode;
23897
23898   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23899   // we're requiring SSE2 for both.
23900   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23901     SDValue N0 = N->getOperand(0);
23902     SDValue N1 = N->getOperand(1);
23903     SDValue CMP0 = N0->getOperand(1);
23904     SDValue CMP1 = N1->getOperand(1);
23905     SDLoc DL(N);
23906
23907     // The SETCCs should both refer to the same CMP.
23908     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23909       return SDValue();
23910
23911     SDValue CMP00 = CMP0->getOperand(0);
23912     SDValue CMP01 = CMP0->getOperand(1);
23913     EVT     VT    = CMP00.getValueType();
23914
23915     if (VT == MVT::f32 || VT == MVT::f64) {
23916       bool ExpectingFlags = false;
23917       // Check for any users that want flags:
23918       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23919            !ExpectingFlags && UI != UE; ++UI)
23920         switch (UI->getOpcode()) {
23921         default:
23922         case ISD::BR_CC:
23923         case ISD::BRCOND:
23924         case ISD::SELECT:
23925           ExpectingFlags = true;
23926           break;
23927         case ISD::CopyToReg:
23928         case ISD::SIGN_EXTEND:
23929         case ISD::ZERO_EXTEND:
23930         case ISD::ANY_EXTEND:
23931           break;
23932         }
23933
23934       if (!ExpectingFlags) {
23935         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23936         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23937
23938         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23939           X86::CondCode tmp = cc0;
23940           cc0 = cc1;
23941           cc1 = tmp;
23942         }
23943
23944         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23945             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23946           // FIXME: need symbolic constants for these magic numbers.
23947           // See X86ATTInstPrinter.cpp:printSSECC().
23948           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23949           if (Subtarget->hasAVX512()) {
23950             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23951                                          CMP01,
23952                                          DAG.getConstant(x86cc, DL, MVT::i8));
23953             if (N->getValueType(0) != MVT::i1)
23954               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23955                                  FSetCC);
23956             return FSetCC;
23957           }
23958           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23959                                               CMP00.getValueType(), CMP00, CMP01,
23960                                               DAG.getConstant(x86cc, DL,
23961                                                               MVT::i8));
23962
23963           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23964           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23965
23966           if (is64BitFP && !Subtarget->is64Bit()) {
23967             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23968             // 64-bit integer, since that's not a legal type. Since
23969             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23970             // bits, but can do this little dance to extract the lowest 32 bits
23971             // and work with those going forward.
23972             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23973                                            OnesOrZeroesF);
23974             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23975             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23976                                         Vector32, DAG.getIntPtrConstant(0, DL));
23977             IntVT = MVT::i32;
23978           }
23979
23980           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23981           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23982                                       DAG.getConstant(1, DL, IntVT));
23983           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23984                                               ANDed);
23985           return OneBitOfTruth;
23986         }
23987       }
23988     }
23989   }
23990   return SDValue();
23991 }
23992
23993 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23994 /// so it can be folded inside ANDNP.
23995 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23996   EVT VT = N->getValueType(0);
23997
23998   // Match direct AllOnes for 128 and 256-bit vectors
23999   if (ISD::isBuildVectorAllOnes(N))
24000     return true;
24001
24002   // Look through a bit convert.
24003   if (N->getOpcode() == ISD::BITCAST)
24004     N = N->getOperand(0).getNode();
24005
24006   // Sometimes the operand may come from a insert_subvector building a 256-bit
24007   // allones vector
24008   if (VT.is256BitVector() &&
24009       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24010     SDValue V1 = N->getOperand(0);
24011     SDValue V2 = N->getOperand(1);
24012
24013     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24014         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24015         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24016         ISD::isBuildVectorAllOnes(V2.getNode()))
24017       return true;
24018   }
24019
24020   return false;
24021 }
24022
24023 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24024 // register. In most cases we actually compare or select YMM-sized registers
24025 // and mixing the two types creates horrible code. This method optimizes
24026 // some of the transition sequences.
24027 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24028                                  TargetLowering::DAGCombinerInfo &DCI,
24029                                  const X86Subtarget *Subtarget) {
24030   EVT VT = N->getValueType(0);
24031   if (!VT.is256BitVector())
24032     return SDValue();
24033
24034   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24035           N->getOpcode() == ISD::ZERO_EXTEND ||
24036           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24037
24038   SDValue Narrow = N->getOperand(0);
24039   EVT NarrowVT = Narrow->getValueType(0);
24040   if (!NarrowVT.is128BitVector())
24041     return SDValue();
24042
24043   if (Narrow->getOpcode() != ISD::XOR &&
24044       Narrow->getOpcode() != ISD::AND &&
24045       Narrow->getOpcode() != ISD::OR)
24046     return SDValue();
24047
24048   SDValue N0  = Narrow->getOperand(0);
24049   SDValue N1  = Narrow->getOperand(1);
24050   SDLoc DL(Narrow);
24051
24052   // The Left side has to be a trunc.
24053   if (N0.getOpcode() != ISD::TRUNCATE)
24054     return SDValue();
24055
24056   // The type of the truncated inputs.
24057   EVT WideVT = N0->getOperand(0)->getValueType(0);
24058   if (WideVT != VT)
24059     return SDValue();
24060
24061   // The right side has to be a 'trunc' or a constant vector.
24062   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24063   ConstantSDNode *RHSConstSplat = nullptr;
24064   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24065     RHSConstSplat = RHSBV->getConstantSplatNode();
24066   if (!RHSTrunc && !RHSConstSplat)
24067     return SDValue();
24068
24069   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24070
24071   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24072     return SDValue();
24073
24074   // Set N0 and N1 to hold the inputs to the new wide operation.
24075   N0 = N0->getOperand(0);
24076   if (RHSConstSplat) {
24077     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24078                      SDValue(RHSConstSplat, 0));
24079     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24080     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24081   } else if (RHSTrunc) {
24082     N1 = N1->getOperand(0);
24083   }
24084
24085   // Generate the wide operation.
24086   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24087   unsigned Opcode = N->getOpcode();
24088   switch (Opcode) {
24089   case ISD::ANY_EXTEND:
24090     return Op;
24091   case ISD::ZERO_EXTEND: {
24092     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24093     APInt Mask = APInt::getAllOnesValue(InBits);
24094     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24095     return DAG.getNode(ISD::AND, DL, VT,
24096                        Op, DAG.getConstant(Mask, DL, VT));
24097   }
24098   case ISD::SIGN_EXTEND:
24099     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24100                        Op, DAG.getValueType(NarrowVT));
24101   default:
24102     llvm_unreachable("Unexpected opcode");
24103   }
24104 }
24105
24106 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24107                                  TargetLowering::DAGCombinerInfo &DCI,
24108                                  const X86Subtarget *Subtarget) {
24109   SDValue N0 = N->getOperand(0);
24110   SDValue N1 = N->getOperand(1);
24111   SDLoc DL(N);
24112
24113   // A vector zext_in_reg may be represented as a shuffle,
24114   // feeding into a bitcast (this represents anyext) feeding into
24115   // an and with a mask.
24116   // We'd like to try to combine that into a shuffle with zero
24117   // plus a bitcast, removing the and.
24118   if (N0.getOpcode() != ISD::BITCAST ||
24119       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24120     return SDValue();
24121
24122   // The other side of the AND should be a splat of 2^C, where C
24123   // is the number of bits in the source type.
24124   if (N1.getOpcode() == ISD::BITCAST)
24125     N1 = N1.getOperand(0);
24126   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24127     return SDValue();
24128   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24129
24130   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24131   EVT SrcType = Shuffle->getValueType(0);
24132
24133   // We expect a single-source shuffle
24134   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24135     return SDValue();
24136
24137   unsigned SrcSize = SrcType.getScalarSizeInBits();
24138
24139   APInt SplatValue, SplatUndef;
24140   unsigned SplatBitSize;
24141   bool HasAnyUndefs;
24142   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24143                                 SplatBitSize, HasAnyUndefs))
24144     return SDValue();
24145
24146   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24147   // Make sure the splat matches the mask we expect
24148   if (SplatBitSize > ResSize ||
24149       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24150     return SDValue();
24151
24152   // Make sure the input and output size make sense
24153   if (SrcSize >= ResSize || ResSize % SrcSize)
24154     return SDValue();
24155
24156   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24157   // The number of u's between each two values depends on the ratio between
24158   // the source and dest type.
24159   unsigned ZextRatio = ResSize / SrcSize;
24160   bool IsZext = true;
24161   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24162     if (i % ZextRatio) {
24163       if (Shuffle->getMaskElt(i) > 0) {
24164         // Expected undef
24165         IsZext = false;
24166         break;
24167       }
24168     } else {
24169       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24170         // Expected element number
24171         IsZext = false;
24172         break;
24173       }
24174     }
24175   }
24176
24177   if (!IsZext)
24178     return SDValue();
24179
24180   // Ok, perform the transformation - replace the shuffle with
24181   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24182   // (instead of undef) where the k elements come from the zero vector.
24183   SmallVector<int, 8> Mask;
24184   unsigned NumElems = SrcType.getVectorNumElements();
24185   for (unsigned i = 0; i < NumElems; ++i)
24186     if (i % ZextRatio)
24187       Mask.push_back(NumElems);
24188     else
24189       Mask.push_back(i / ZextRatio);
24190
24191   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24192     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24193   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24194 }
24195
24196 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24197                                  TargetLowering::DAGCombinerInfo &DCI,
24198                                  const X86Subtarget *Subtarget) {
24199   if (DCI.isBeforeLegalizeOps())
24200     return SDValue();
24201
24202   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24203     return Zext;
24204
24205   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24206     return R;
24207
24208   EVT VT = N->getValueType(0);
24209   SDValue N0 = N->getOperand(0);
24210   SDValue N1 = N->getOperand(1);
24211   SDLoc DL(N);
24212
24213   // Create BEXTR instructions
24214   // BEXTR is ((X >> imm) & (2**size-1))
24215   if (VT == MVT::i32 || VT == MVT::i64) {
24216     // Check for BEXTR.
24217     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24218         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24219       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24220       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24221       if (MaskNode && ShiftNode) {
24222         uint64_t Mask = MaskNode->getZExtValue();
24223         uint64_t Shift = ShiftNode->getZExtValue();
24224         if (isMask_64(Mask)) {
24225           uint64_t MaskSize = countPopulation(Mask);
24226           if (Shift + MaskSize <= VT.getSizeInBits())
24227             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24228                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24229                                                VT));
24230         }
24231       }
24232     } // BEXTR
24233
24234     return SDValue();
24235   }
24236
24237   // Want to form ANDNP nodes:
24238   // 1) In the hopes of then easily combining them with OR and AND nodes
24239   //    to form PBLEND/PSIGN.
24240   // 2) To match ANDN packed intrinsics
24241   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24242     return SDValue();
24243
24244   // Check LHS for vnot
24245   if (N0.getOpcode() == ISD::XOR &&
24246       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24247       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24248     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24249
24250   // Check RHS for vnot
24251   if (N1.getOpcode() == ISD::XOR &&
24252       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24253       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24254     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24255
24256   return SDValue();
24257 }
24258
24259 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24260                                 TargetLowering::DAGCombinerInfo &DCI,
24261                                 const X86Subtarget *Subtarget) {
24262   if (DCI.isBeforeLegalizeOps())
24263     return SDValue();
24264
24265   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24266     return R;
24267
24268   SDValue N0 = N->getOperand(0);
24269   SDValue N1 = N->getOperand(1);
24270   EVT VT = N->getValueType(0);
24271
24272   // look for psign/blend
24273   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24274     if (!Subtarget->hasSSSE3() ||
24275         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24276       return SDValue();
24277
24278     // Canonicalize pandn to RHS
24279     if (N0.getOpcode() == X86ISD::ANDNP)
24280       std::swap(N0, N1);
24281     // or (and (m, y), (pandn m, x))
24282     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24283       SDValue Mask = N1.getOperand(0);
24284       SDValue X    = N1.getOperand(1);
24285       SDValue Y;
24286       if (N0.getOperand(0) == Mask)
24287         Y = N0.getOperand(1);
24288       if (N0.getOperand(1) == Mask)
24289         Y = N0.getOperand(0);
24290
24291       // Check to see if the mask appeared in both the AND and ANDNP and
24292       if (!Y.getNode())
24293         return SDValue();
24294
24295       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24296       // Look through mask bitcast.
24297       if (Mask.getOpcode() == ISD::BITCAST)
24298         Mask = Mask.getOperand(0);
24299       if (X.getOpcode() == ISD::BITCAST)
24300         X = X.getOperand(0);
24301       if (Y.getOpcode() == ISD::BITCAST)
24302         Y = Y.getOperand(0);
24303
24304       EVT MaskVT = Mask.getValueType();
24305
24306       // Validate that the Mask operand is a vector sra node.
24307       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24308       // there is no psrai.b
24309       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24310       unsigned SraAmt = ~0;
24311       if (Mask.getOpcode() == ISD::SRA) {
24312         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24313           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24314             SraAmt = AmtConst->getZExtValue();
24315       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24316         SDValue SraC = Mask.getOperand(1);
24317         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24318       }
24319       if ((SraAmt + 1) != EltBits)
24320         return SDValue();
24321
24322       SDLoc DL(N);
24323
24324       // Now we know we at least have a plendvb with the mask val.  See if
24325       // we can form a psignb/w/d.
24326       // psign = x.type == y.type == mask.type && y = sub(0, x);
24327       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24328           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24329           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24330         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24331                "Unsupported VT for PSIGN");
24332         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24333         return DAG.getBitcast(VT, Mask);
24334       }
24335       // PBLENDVB only available on SSE 4.1
24336       if (!Subtarget->hasSSE41())
24337         return SDValue();
24338
24339       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24340
24341       X = DAG.getBitcast(BlendVT, X);
24342       Y = DAG.getBitcast(BlendVT, Y);
24343       Mask = DAG.getBitcast(BlendVT, Mask);
24344       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24345       return DAG.getBitcast(VT, Mask);
24346     }
24347   }
24348
24349   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24350     return SDValue();
24351
24352   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24353   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24354
24355   // SHLD/SHRD instructions have lower register pressure, but on some
24356   // platforms they have higher latency than the equivalent
24357   // series of shifts/or that would otherwise be generated.
24358   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24359   // have higher latencies and we are not optimizing for size.
24360   if (!OptForSize && Subtarget->isSHLDSlow())
24361     return SDValue();
24362
24363   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24364     std::swap(N0, N1);
24365   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24366     return SDValue();
24367   if (!N0.hasOneUse() || !N1.hasOneUse())
24368     return SDValue();
24369
24370   SDValue ShAmt0 = N0.getOperand(1);
24371   if (ShAmt0.getValueType() != MVT::i8)
24372     return SDValue();
24373   SDValue ShAmt1 = N1.getOperand(1);
24374   if (ShAmt1.getValueType() != MVT::i8)
24375     return SDValue();
24376   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24377     ShAmt0 = ShAmt0.getOperand(0);
24378   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24379     ShAmt1 = ShAmt1.getOperand(0);
24380
24381   SDLoc DL(N);
24382   unsigned Opc = X86ISD::SHLD;
24383   SDValue Op0 = N0.getOperand(0);
24384   SDValue Op1 = N1.getOperand(0);
24385   if (ShAmt0.getOpcode() == ISD::SUB) {
24386     Opc = X86ISD::SHRD;
24387     std::swap(Op0, Op1);
24388     std::swap(ShAmt0, ShAmt1);
24389   }
24390
24391   unsigned Bits = VT.getSizeInBits();
24392   if (ShAmt1.getOpcode() == ISD::SUB) {
24393     SDValue Sum = ShAmt1.getOperand(0);
24394     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24395       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24396       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24397         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24398       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24399         return DAG.getNode(Opc, DL, VT,
24400                            Op0, Op1,
24401                            DAG.getNode(ISD::TRUNCATE, DL,
24402                                        MVT::i8, ShAmt0));
24403     }
24404   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24405     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24406     if (ShAmt0C &&
24407         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24408       return DAG.getNode(Opc, DL, VT,
24409                          N0.getOperand(0), N1.getOperand(0),
24410                          DAG.getNode(ISD::TRUNCATE, DL,
24411                                        MVT::i8, ShAmt0));
24412   }
24413
24414   return SDValue();
24415 }
24416
24417 // Generate NEG and CMOV for integer abs.
24418 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24419   EVT VT = N->getValueType(0);
24420
24421   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24422   // 8-bit integer abs to NEG and CMOV.
24423   if (VT.isInteger() && VT.getSizeInBits() == 8)
24424     return SDValue();
24425
24426   SDValue N0 = N->getOperand(0);
24427   SDValue N1 = N->getOperand(1);
24428   SDLoc DL(N);
24429
24430   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24431   // and change it to SUB and CMOV.
24432   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24433       N0.getOpcode() == ISD::ADD &&
24434       N0.getOperand(1) == N1 &&
24435       N1.getOpcode() == ISD::SRA &&
24436       N1.getOperand(0) == N0.getOperand(0))
24437     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24438       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24439         // Generate SUB & CMOV.
24440         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24441                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24442
24443         SDValue Ops[] = { N0.getOperand(0), Neg,
24444                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24445                           SDValue(Neg.getNode(), 1) };
24446         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24447       }
24448   return SDValue();
24449 }
24450
24451 // Try to turn tests against the signbit in the form of:
24452 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24453 // into:
24454 //   SETGT(X, -1)
24455 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24456   // This is only worth doing if the output type is i8.
24457   if (N->getValueType(0) != MVT::i8)
24458     return SDValue();
24459
24460   SDValue N0 = N->getOperand(0);
24461   SDValue N1 = N->getOperand(1);
24462
24463   // We should be performing an xor against a truncated shift.
24464   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24465     return SDValue();
24466
24467   // Make sure we are performing an xor against one.
24468   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24469     return SDValue();
24470
24471   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24472   SDValue Shift = N0.getOperand(0);
24473   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24474     return SDValue();
24475
24476   // Make sure we are truncating from one of i16, i32 or i64.
24477   EVT ShiftTy = Shift.getValueType();
24478   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24479     return SDValue();
24480
24481   // Make sure the shift amount extracts the sign bit.
24482   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24483       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24484     return SDValue();
24485
24486   // Create a greater-than comparison against -1.
24487   // N.B. Using SETGE against 0 works but we want a canonical looking
24488   // comparison, using SETGT matches up with what TranslateX86CC.
24489   SDLoc DL(N);
24490   SDValue ShiftOp = Shift.getOperand(0);
24491   EVT ShiftOpTy = ShiftOp.getValueType();
24492   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24493                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24494   return Cond;
24495 }
24496
24497 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24498                                  TargetLowering::DAGCombinerInfo &DCI,
24499                                  const X86Subtarget *Subtarget) {
24500   if (DCI.isBeforeLegalizeOps())
24501     return SDValue();
24502
24503   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24504     return RV;
24505
24506   if (Subtarget->hasCMov())
24507     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24508       return RV;
24509
24510   return SDValue();
24511 }
24512
24513 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24514 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24515                                   TargetLowering::DAGCombinerInfo &DCI,
24516                                   const X86Subtarget *Subtarget) {
24517   LoadSDNode *Ld = cast<LoadSDNode>(N);
24518   EVT RegVT = Ld->getValueType(0);
24519   EVT MemVT = Ld->getMemoryVT();
24520   SDLoc dl(Ld);
24521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24522
24523   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24524   // into two 16-byte operations.
24525   ISD::LoadExtType Ext = Ld->getExtensionType();
24526   bool Fast;
24527   unsigned AddressSpace = Ld->getAddressSpace();
24528   unsigned Alignment = Ld->getAlignment();
24529   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24530       Ext == ISD::NON_EXTLOAD &&
24531       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24532                              AddressSpace, Alignment, &Fast) && !Fast) {
24533     unsigned NumElems = RegVT.getVectorNumElements();
24534     if (NumElems < 2)
24535       return SDValue();
24536
24537     SDValue Ptr = Ld->getBasePtr();
24538     SDValue Increment =
24539         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24540
24541     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24542                                   NumElems/2);
24543     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24544                                 Ld->getPointerInfo(), Ld->isVolatile(),
24545                                 Ld->isNonTemporal(), Ld->isInvariant(),
24546                                 Alignment);
24547     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24548     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24549                                 Ld->getPointerInfo(), Ld->isVolatile(),
24550                                 Ld->isNonTemporal(), Ld->isInvariant(),
24551                                 std::min(16U, Alignment));
24552     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24553                              Load1.getValue(1),
24554                              Load2.getValue(1));
24555
24556     SDValue NewVec = DAG.getUNDEF(RegVT);
24557     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24558     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24559     return DCI.CombineTo(N, NewVec, TF, true);
24560   }
24561
24562   return SDValue();
24563 }
24564
24565 /// PerformMLOADCombine - Resolve extending loads
24566 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24567                                    TargetLowering::DAGCombinerInfo &DCI,
24568                                    const X86Subtarget *Subtarget) {
24569   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24570   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24571     return SDValue();
24572
24573   EVT VT = Mld->getValueType(0);
24574   unsigned NumElems = VT.getVectorNumElements();
24575   EVT LdVT = Mld->getMemoryVT();
24576   SDLoc dl(Mld);
24577
24578   assert(LdVT != VT && "Cannot extend to the same type");
24579   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24580   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24581   // From, To sizes and ElemCount must be pow of two
24582   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24583     "Unexpected size for extending masked load");
24584
24585   unsigned SizeRatio  = ToSz / FromSz;
24586   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24587
24588   // Create a type on which we perform the shuffle
24589   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24590           LdVT.getScalarType(), NumElems*SizeRatio);
24591   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24592
24593   // Convert Src0 value
24594   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24595   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24596     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24597     for (unsigned i = 0; i != NumElems; ++i)
24598       ShuffleVec[i] = i * SizeRatio;
24599
24600     // Can't shuffle using an illegal type.
24601     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24602             && "WideVecVT should be legal");
24603     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24604                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24605   }
24606   // Prepare the new mask
24607   SDValue NewMask;
24608   SDValue Mask = Mld->getMask();
24609   if (Mask.getValueType() == VT) {
24610     // Mask and original value have the same type
24611     NewMask = DAG.getBitcast(WideVecVT, Mask);
24612     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24613     for (unsigned i = 0; i != NumElems; ++i)
24614       ShuffleVec[i] = i * SizeRatio;
24615     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24616       ShuffleVec[i] = NumElems*SizeRatio;
24617     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24618                                    DAG.getConstant(0, dl, WideVecVT),
24619                                    &ShuffleVec[0]);
24620   }
24621   else {
24622     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24623     unsigned WidenNumElts = NumElems*SizeRatio;
24624     unsigned MaskNumElts = VT.getVectorNumElements();
24625     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24626                                      WidenNumElts);
24627
24628     unsigned NumConcat = WidenNumElts / MaskNumElts;
24629     SmallVector<SDValue, 16> Ops(NumConcat);
24630     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24631     Ops[0] = Mask;
24632     for (unsigned i = 1; i != NumConcat; ++i)
24633       Ops[i] = ZeroVal;
24634
24635     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24636   }
24637
24638   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24639                                      Mld->getBasePtr(), NewMask, WideSrc0,
24640                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24641                                      ISD::NON_EXTLOAD);
24642   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24643   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24644
24645 }
24646 /// PerformMSTORECombine - Resolve truncating stores
24647 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24648                                     const X86Subtarget *Subtarget) {
24649   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24650   if (!Mst->isTruncatingStore())
24651     return SDValue();
24652
24653   EVT VT = Mst->getValue().getValueType();
24654   unsigned NumElems = VT.getVectorNumElements();
24655   EVT StVT = Mst->getMemoryVT();
24656   SDLoc dl(Mst);
24657
24658   assert(StVT != VT && "Cannot truncate to the same type");
24659   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24660   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24661
24662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24663
24664   // The truncating store is legal in some cases. For example
24665   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24666   // are designated for truncate store.
24667   // In this case we don't need any further transformations.
24668   if (TLI.isTruncStoreLegal(VT, StVT))
24669     return SDValue();
24670
24671   // From, To sizes and ElemCount must be pow of two
24672   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24673     "Unexpected size for truncating masked store");
24674   // We are going to use the original vector elt for storing.
24675   // Accumulated smaller vector elements must be a multiple of the store size.
24676   assert (((NumElems * FromSz) % ToSz) == 0 &&
24677           "Unexpected ratio for truncating masked store");
24678
24679   unsigned SizeRatio  = FromSz / ToSz;
24680   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24681
24682   // Create a type on which we perform the shuffle
24683   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24684           StVT.getScalarType(), NumElems*SizeRatio);
24685
24686   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24687
24688   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24689   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24690   for (unsigned i = 0; i != NumElems; ++i)
24691     ShuffleVec[i] = i * SizeRatio;
24692
24693   // Can't shuffle using an illegal type.
24694   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24695           && "WideVecVT should be legal");
24696
24697   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24698                                         DAG.getUNDEF(WideVecVT),
24699                                         &ShuffleVec[0]);
24700
24701   SDValue NewMask;
24702   SDValue Mask = Mst->getMask();
24703   if (Mask.getValueType() == VT) {
24704     // Mask and original value have the same type
24705     NewMask = DAG.getBitcast(WideVecVT, Mask);
24706     for (unsigned i = 0; i != NumElems; ++i)
24707       ShuffleVec[i] = i * SizeRatio;
24708     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24709       ShuffleVec[i] = NumElems*SizeRatio;
24710     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24711                                    DAG.getConstant(0, dl, WideVecVT),
24712                                    &ShuffleVec[0]);
24713   }
24714   else {
24715     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24716     unsigned WidenNumElts = NumElems*SizeRatio;
24717     unsigned MaskNumElts = VT.getVectorNumElements();
24718     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24719                                      WidenNumElts);
24720
24721     unsigned NumConcat = WidenNumElts / MaskNumElts;
24722     SmallVector<SDValue, 16> Ops(NumConcat);
24723     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24724     Ops[0] = Mask;
24725     for (unsigned i = 1; i != NumConcat; ++i)
24726       Ops[i] = ZeroVal;
24727
24728     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24729   }
24730
24731   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24732                             NewMask, StVT, Mst->getMemOperand(), false);
24733 }
24734 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24735 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24736                                    const X86Subtarget *Subtarget) {
24737   StoreSDNode *St = cast<StoreSDNode>(N);
24738   EVT VT = St->getValue().getValueType();
24739   EVT StVT = St->getMemoryVT();
24740   SDLoc dl(St);
24741   SDValue StoredVal = St->getOperand(1);
24742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24743
24744   // If we are saving a concatenation of two XMM registers and 32-byte stores
24745   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24746   bool Fast;
24747   unsigned AddressSpace = St->getAddressSpace();
24748   unsigned Alignment = St->getAlignment();
24749   if (VT.is256BitVector() && StVT == VT &&
24750       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24751                              AddressSpace, Alignment, &Fast) && !Fast) {
24752     unsigned NumElems = VT.getVectorNumElements();
24753     if (NumElems < 2)
24754       return SDValue();
24755
24756     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24757     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24758
24759     SDValue Stride =
24760         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24761     SDValue Ptr0 = St->getBasePtr();
24762     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24763
24764     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24765                                 St->getPointerInfo(), St->isVolatile(),
24766                                 St->isNonTemporal(), Alignment);
24767     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24768                                 St->getPointerInfo(), St->isVolatile(),
24769                                 St->isNonTemporal(),
24770                                 std::min(16U, Alignment));
24771     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24772   }
24773
24774   // Optimize trunc store (of multiple scalars) to shuffle and store.
24775   // First, pack all of the elements in one place. Next, store to memory
24776   // in fewer chunks.
24777   if (St->isTruncatingStore() && VT.isVector()) {
24778     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24779     unsigned NumElems = VT.getVectorNumElements();
24780     assert(StVT != VT && "Cannot truncate to the same type");
24781     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24782     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24783
24784     // The truncating store is legal in some cases. For example
24785     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24786     // are designated for truncate store.
24787     // In this case we don't need any further transformations.
24788     if (TLI.isTruncStoreLegal(VT, StVT))
24789       return SDValue();
24790
24791     // From, To sizes and ElemCount must be pow of two
24792     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24793     // We are going to use the original vector elt for storing.
24794     // Accumulated smaller vector elements must be a multiple of the store size.
24795     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24796
24797     unsigned SizeRatio  = FromSz / ToSz;
24798
24799     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24800
24801     // Create a type on which we perform the shuffle
24802     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24803             StVT.getScalarType(), NumElems*SizeRatio);
24804
24805     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24806
24807     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24808     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24809     for (unsigned i = 0; i != NumElems; ++i)
24810       ShuffleVec[i] = i * SizeRatio;
24811
24812     // Can't shuffle using an illegal type.
24813     if (!TLI.isTypeLegal(WideVecVT))
24814       return SDValue();
24815
24816     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24817                                          DAG.getUNDEF(WideVecVT),
24818                                          &ShuffleVec[0]);
24819     // At this point all of the data is stored at the bottom of the
24820     // register. We now need to save it to mem.
24821
24822     // Find the largest store unit
24823     MVT StoreType = MVT::i8;
24824     for (MVT Tp : MVT::integer_valuetypes()) {
24825       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24826         StoreType = Tp;
24827     }
24828
24829     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24830     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24831         (64 <= NumElems * ToSz))
24832       StoreType = MVT::f64;
24833
24834     // Bitcast the original vector into a vector of store-size units
24835     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24836             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24837     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24838     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24839     SmallVector<SDValue, 8> Chains;
24840     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24841                                         TLI.getPointerTy(DAG.getDataLayout()));
24842     SDValue Ptr = St->getBasePtr();
24843
24844     // Perform one or more big stores into memory.
24845     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24846       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24847                                    StoreType, ShuffWide,
24848                                    DAG.getIntPtrConstant(i, dl));
24849       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24850                                 St->getPointerInfo(), St->isVolatile(),
24851                                 St->isNonTemporal(), St->getAlignment());
24852       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24853       Chains.push_back(Ch);
24854     }
24855
24856     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24857   }
24858
24859   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24860   // the FP state in cases where an emms may be missing.
24861   // A preferable solution to the general problem is to figure out the right
24862   // places to insert EMMS.  This qualifies as a quick hack.
24863
24864   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24865   if (VT.getSizeInBits() != 64)
24866     return SDValue();
24867
24868   const Function *F = DAG.getMachineFunction().getFunction();
24869   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24870   bool F64IsLegal =
24871       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24872   if ((VT.isVector() ||
24873        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24874       isa<LoadSDNode>(St->getValue()) &&
24875       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24876       St->getChain().hasOneUse() && !St->isVolatile()) {
24877     SDNode* LdVal = St->getValue().getNode();
24878     LoadSDNode *Ld = nullptr;
24879     int TokenFactorIndex = -1;
24880     SmallVector<SDValue, 8> Ops;
24881     SDNode* ChainVal = St->getChain().getNode();
24882     // Must be a store of a load.  We currently handle two cases:  the load
24883     // is a direct child, and it's under an intervening TokenFactor.  It is
24884     // possible to dig deeper under nested TokenFactors.
24885     if (ChainVal == LdVal)
24886       Ld = cast<LoadSDNode>(St->getChain());
24887     else if (St->getValue().hasOneUse() &&
24888              ChainVal->getOpcode() == ISD::TokenFactor) {
24889       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24890         if (ChainVal->getOperand(i).getNode() == LdVal) {
24891           TokenFactorIndex = i;
24892           Ld = cast<LoadSDNode>(St->getValue());
24893         } else
24894           Ops.push_back(ChainVal->getOperand(i));
24895       }
24896     }
24897
24898     if (!Ld || !ISD::isNormalLoad(Ld))
24899       return SDValue();
24900
24901     // If this is not the MMX case, i.e. we are just turning i64 load/store
24902     // into f64 load/store, avoid the transformation if there are multiple
24903     // uses of the loaded value.
24904     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24905       return SDValue();
24906
24907     SDLoc LdDL(Ld);
24908     SDLoc StDL(N);
24909     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24910     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24911     // pair instead.
24912     if (Subtarget->is64Bit() || F64IsLegal) {
24913       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24914       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24915                                   Ld->getPointerInfo(), Ld->isVolatile(),
24916                                   Ld->isNonTemporal(), Ld->isInvariant(),
24917                                   Ld->getAlignment());
24918       SDValue NewChain = NewLd.getValue(1);
24919       if (TokenFactorIndex != -1) {
24920         Ops.push_back(NewChain);
24921         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24922       }
24923       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24924                           St->getPointerInfo(),
24925                           St->isVolatile(), St->isNonTemporal(),
24926                           St->getAlignment());
24927     }
24928
24929     // Otherwise, lower to two pairs of 32-bit loads / stores.
24930     SDValue LoAddr = Ld->getBasePtr();
24931     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24932                                  DAG.getConstant(4, LdDL, MVT::i32));
24933
24934     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24935                                Ld->getPointerInfo(),
24936                                Ld->isVolatile(), Ld->isNonTemporal(),
24937                                Ld->isInvariant(), Ld->getAlignment());
24938     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24939                                Ld->getPointerInfo().getWithOffset(4),
24940                                Ld->isVolatile(), Ld->isNonTemporal(),
24941                                Ld->isInvariant(),
24942                                MinAlign(Ld->getAlignment(), 4));
24943
24944     SDValue NewChain = LoLd.getValue(1);
24945     if (TokenFactorIndex != -1) {
24946       Ops.push_back(LoLd);
24947       Ops.push_back(HiLd);
24948       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24949     }
24950
24951     LoAddr = St->getBasePtr();
24952     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24953                          DAG.getConstant(4, StDL, MVT::i32));
24954
24955     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24956                                 St->getPointerInfo(),
24957                                 St->isVolatile(), St->isNonTemporal(),
24958                                 St->getAlignment());
24959     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24960                                 St->getPointerInfo().getWithOffset(4),
24961                                 St->isVolatile(),
24962                                 St->isNonTemporal(),
24963                                 MinAlign(St->getAlignment(), 4));
24964     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24965   }
24966
24967   // This is similar to the above case, but here we handle a scalar 64-bit
24968   // integer store that is extracted from a vector on a 32-bit target.
24969   // If we have SSE2, then we can treat it like a floating-point double
24970   // to get past legalization. The execution dependencies fixup pass will
24971   // choose the optimal machine instruction for the store if this really is
24972   // an integer or v2f32 rather than an f64.
24973   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24974       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24975     SDValue OldExtract = St->getOperand(1);
24976     SDValue ExtOp0 = OldExtract.getOperand(0);
24977     unsigned VecSize = ExtOp0.getValueSizeInBits();
24978     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24979     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24980     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24981                                      BitCast, OldExtract.getOperand(1));
24982     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24983                         St->getPointerInfo(), St->isVolatile(),
24984                         St->isNonTemporal(), St->getAlignment());
24985   }
24986
24987   return SDValue();
24988 }
24989
24990 /// Return 'true' if this vector operation is "horizontal"
24991 /// and return the operands for the horizontal operation in LHS and RHS.  A
24992 /// horizontal operation performs the binary operation on successive elements
24993 /// of its first operand, then on successive elements of its second operand,
24994 /// returning the resulting values in a vector.  For example, if
24995 ///   A = < float a0, float a1, float a2, float a3 >
24996 /// and
24997 ///   B = < float b0, float b1, float b2, float b3 >
24998 /// then the result of doing a horizontal operation on A and B is
24999 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25000 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25001 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25002 /// set to A, RHS to B, and the routine returns 'true'.
25003 /// Note that the binary operation should have the property that if one of the
25004 /// operands is UNDEF then the result is UNDEF.
25005 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25006   // Look for the following pattern: if
25007   //   A = < float a0, float a1, float a2, float a3 >
25008   //   B = < float b0, float b1, float b2, float b3 >
25009   // and
25010   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25011   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25012   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25013   // which is A horizontal-op B.
25014
25015   // At least one of the operands should be a vector shuffle.
25016   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25017       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25018     return false;
25019
25020   MVT VT = LHS.getSimpleValueType();
25021
25022   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25023          "Unsupported vector type for horizontal add/sub");
25024
25025   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25026   // operate independently on 128-bit lanes.
25027   unsigned NumElts = VT.getVectorNumElements();
25028   unsigned NumLanes = VT.getSizeInBits()/128;
25029   unsigned NumLaneElts = NumElts / NumLanes;
25030   assert((NumLaneElts % 2 == 0) &&
25031          "Vector type should have an even number of elements in each lane");
25032   unsigned HalfLaneElts = NumLaneElts/2;
25033
25034   // View LHS in the form
25035   //   LHS = VECTOR_SHUFFLE A, B, LMask
25036   // If LHS is not a shuffle then pretend it is the shuffle
25037   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25038   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25039   // type VT.
25040   SDValue A, B;
25041   SmallVector<int, 16> LMask(NumElts);
25042   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25043     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25044       A = LHS.getOperand(0);
25045     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25046       B = LHS.getOperand(1);
25047     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25048     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25049   } else {
25050     if (LHS.getOpcode() != ISD::UNDEF)
25051       A = LHS;
25052     for (unsigned i = 0; i != NumElts; ++i)
25053       LMask[i] = i;
25054   }
25055
25056   // Likewise, view RHS in the form
25057   //   RHS = VECTOR_SHUFFLE C, D, RMask
25058   SDValue C, D;
25059   SmallVector<int, 16> RMask(NumElts);
25060   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25061     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25062       C = RHS.getOperand(0);
25063     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25064       D = RHS.getOperand(1);
25065     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25066     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25067   } else {
25068     if (RHS.getOpcode() != ISD::UNDEF)
25069       C = RHS;
25070     for (unsigned i = 0; i != NumElts; ++i)
25071       RMask[i] = i;
25072   }
25073
25074   // Check that the shuffles are both shuffling the same vectors.
25075   if (!(A == C && B == D) && !(A == D && B == C))
25076     return false;
25077
25078   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25079   if (!A.getNode() && !B.getNode())
25080     return false;
25081
25082   // If A and B occur in reverse order in RHS, then "swap" them (which means
25083   // rewriting the mask).
25084   if (A != C)
25085     ShuffleVectorSDNode::commuteMask(RMask);
25086
25087   // At this point LHS and RHS are equivalent to
25088   //   LHS = VECTOR_SHUFFLE A, B, LMask
25089   //   RHS = VECTOR_SHUFFLE A, B, RMask
25090   // Check that the masks correspond to performing a horizontal operation.
25091   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25092     for (unsigned i = 0; i != NumLaneElts; ++i) {
25093       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25094
25095       // Ignore any UNDEF components.
25096       if (LIdx < 0 || RIdx < 0 ||
25097           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25098           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25099         continue;
25100
25101       // Check that successive elements are being operated on.  If not, this is
25102       // not a horizontal operation.
25103       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25104       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25105       if (!(LIdx == Index && RIdx == Index + 1) &&
25106           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25107         return false;
25108     }
25109   }
25110
25111   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25112   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25113   return true;
25114 }
25115
25116 /// Do target-specific dag combines on floating point adds.
25117 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25118                                   const X86Subtarget *Subtarget) {
25119   EVT VT = N->getValueType(0);
25120   SDValue LHS = N->getOperand(0);
25121   SDValue RHS = N->getOperand(1);
25122
25123   // Try to synthesize horizontal adds from adds of shuffles.
25124   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25125        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25126       isHorizontalBinOp(LHS, RHS, true))
25127     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25128   return SDValue();
25129 }
25130
25131 /// Do target-specific dag combines on floating point subs.
25132 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25133                                   const X86Subtarget *Subtarget) {
25134   EVT VT = N->getValueType(0);
25135   SDValue LHS = N->getOperand(0);
25136   SDValue RHS = N->getOperand(1);
25137
25138   // Try to synthesize horizontal subs from subs of shuffles.
25139   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25140        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25141       isHorizontalBinOp(LHS, RHS, false))
25142     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25143   return SDValue();
25144 }
25145
25146 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25147 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
25148   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25149
25150   // F[X]OR(0.0, x) -> x
25151   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25152     if (C->getValueAPF().isPosZero())
25153       return N->getOperand(1);
25154
25155   // F[X]OR(x, 0.0) -> x
25156   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25157     if (C->getValueAPF().isPosZero())
25158       return N->getOperand(0);
25159   return SDValue();
25160 }
25161
25162 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25163 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25164   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25165
25166   // Only perform optimizations if UnsafeMath is used.
25167   if (!DAG.getTarget().Options.UnsafeFPMath)
25168     return SDValue();
25169
25170   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25171   // into FMINC and FMAXC, which are Commutative operations.
25172   unsigned NewOp = 0;
25173   switch (N->getOpcode()) {
25174     default: llvm_unreachable("unknown opcode");
25175     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25176     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25177   }
25178
25179   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25180                      N->getOperand(0), N->getOperand(1));
25181 }
25182
25183 /// Do target-specific dag combines on X86ISD::FAND nodes.
25184 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25185   // FAND(0.0, x) -> 0.0
25186   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25187     if (C->getValueAPF().isPosZero())
25188       return N->getOperand(0);
25189
25190   // FAND(x, 0.0) -> 0.0
25191   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25192     if (C->getValueAPF().isPosZero())
25193       return N->getOperand(1);
25194
25195   return SDValue();
25196 }
25197
25198 /// Do target-specific dag combines on X86ISD::FANDN nodes
25199 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25200   // FANDN(0.0, x) -> x
25201   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25202     if (C->getValueAPF().isPosZero())
25203       return N->getOperand(1);
25204
25205   // FANDN(x, 0.0) -> 0.0
25206   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25207     if (C->getValueAPF().isPosZero())
25208       return N->getOperand(1);
25209
25210   return SDValue();
25211 }
25212
25213 static SDValue PerformBTCombine(SDNode *N,
25214                                 SelectionDAG &DAG,
25215                                 TargetLowering::DAGCombinerInfo &DCI) {
25216   // BT ignores high bits in the bit index operand.
25217   SDValue Op1 = N->getOperand(1);
25218   if (Op1.hasOneUse()) {
25219     unsigned BitWidth = Op1.getValueSizeInBits();
25220     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25221     APInt KnownZero, KnownOne;
25222     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25223                                           !DCI.isBeforeLegalizeOps());
25224     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25225     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25226         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25227       DCI.CommitTargetLoweringOpt(TLO);
25228   }
25229   return SDValue();
25230 }
25231
25232 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25233   SDValue Op = N->getOperand(0);
25234   if (Op.getOpcode() == ISD::BITCAST)
25235     Op = Op.getOperand(0);
25236   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25237   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25238       VT.getVectorElementType().getSizeInBits() ==
25239       OpVT.getVectorElementType().getSizeInBits()) {
25240     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25241   }
25242   return SDValue();
25243 }
25244
25245 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25246                                                const X86Subtarget *Subtarget) {
25247   EVT VT = N->getValueType(0);
25248   if (!VT.isVector())
25249     return SDValue();
25250
25251   SDValue N0 = N->getOperand(0);
25252   SDValue N1 = N->getOperand(1);
25253   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25254   SDLoc dl(N);
25255
25256   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25257   // both SSE and AVX2 since there is no sign-extended shift right
25258   // operation on a vector with 64-bit elements.
25259   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25260   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25261   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25262       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25263     SDValue N00 = N0.getOperand(0);
25264
25265     // EXTLOAD has a better solution on AVX2,
25266     // it may be replaced with X86ISD::VSEXT node.
25267     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25268       if (!ISD::isNormalLoad(N00.getNode()))
25269         return SDValue();
25270
25271     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25272         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25273                                   N00, N1);
25274       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25275     }
25276   }
25277   return SDValue();
25278 }
25279
25280 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25281                                   TargetLowering::DAGCombinerInfo &DCI,
25282                                   const X86Subtarget *Subtarget) {
25283   SDValue N0 = N->getOperand(0);
25284   EVT VT = N->getValueType(0);
25285   EVT SVT = VT.getScalarType();
25286   EVT InVT = N0.getValueType();
25287   EVT InSVT = InVT.getScalarType();
25288   SDLoc DL(N);
25289
25290   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25291   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25292   // This exposes the sext to the sdivrem lowering, so that it directly extends
25293   // from AH (which we otherwise need to do contortions to access).
25294   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25295       InVT == MVT::i8 && VT == MVT::i32) {
25296     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25297     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25298                             N0.getOperand(0), N0.getOperand(1));
25299     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25300     return R.getValue(1);
25301   }
25302
25303   if (!DCI.isBeforeLegalizeOps()) {
25304     if (InVT == MVT::i1) {
25305       SDValue Zero = DAG.getConstant(0, DL, VT);
25306       SDValue AllOnes =
25307         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25308       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25309     }
25310     return SDValue();
25311   }
25312
25313   if (VT.isVector() && Subtarget->hasSSE2()) {
25314     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25315       EVT InVT = N.getValueType();
25316       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25317                                    Size / InVT.getScalarSizeInBits());
25318       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25319                                     DAG.getUNDEF(InVT));
25320       Opnds[0] = N;
25321       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25322     };
25323
25324     // If target-size is less than 128-bits, extend to a type that would extend
25325     // to 128 bits, extend that and extract the original target vector.
25326     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25327         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25328         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25329       unsigned Scale = 128 / VT.getSizeInBits();
25330       EVT ExVT =
25331           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25332       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25333       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25334       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25335                          DAG.getIntPtrConstant(0, DL));
25336     }
25337
25338     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25339     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25340     if (VT.getSizeInBits() == 128 &&
25341         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25342         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25343       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25344       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25345     }
25346
25347     // On pre-AVX2 targets, split into 128-bit nodes of
25348     // ISD::SIGN_EXTEND_VECTOR_INREG.
25349     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25350         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25351         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25352       unsigned NumVecs = VT.getSizeInBits() / 128;
25353       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25354       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25355       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25356
25357       SmallVector<SDValue, 8> Opnds;
25358       for (unsigned i = 0, Offset = 0; i != NumVecs;
25359            ++i, Offset += NumSubElts) {
25360         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25361                                      DAG.getIntPtrConstant(Offset, DL));
25362         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25363         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25364         Opnds.push_back(SrcVec);
25365       }
25366       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25367     }
25368   }
25369
25370   if (!Subtarget->hasFp256())
25371     return SDValue();
25372
25373   if (VT.isVector() && VT.getSizeInBits() == 256)
25374     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25375       return R;
25376
25377   return SDValue();
25378 }
25379
25380 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25381                                  const X86Subtarget* Subtarget) {
25382   SDLoc dl(N);
25383   EVT VT = N->getValueType(0);
25384
25385   // Let legalize expand this if it isn't a legal type yet.
25386   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25387     return SDValue();
25388
25389   EVT ScalarVT = VT.getScalarType();
25390   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25391       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25392        !Subtarget->hasAVX512()))
25393     return SDValue();
25394
25395   SDValue A = N->getOperand(0);
25396   SDValue B = N->getOperand(1);
25397   SDValue C = N->getOperand(2);
25398
25399   bool NegA = (A.getOpcode() == ISD::FNEG);
25400   bool NegB = (B.getOpcode() == ISD::FNEG);
25401   bool NegC = (C.getOpcode() == ISD::FNEG);
25402
25403   // Negative multiplication when NegA xor NegB
25404   bool NegMul = (NegA != NegB);
25405   if (NegA)
25406     A = A.getOperand(0);
25407   if (NegB)
25408     B = B.getOperand(0);
25409   if (NegC)
25410     C = C.getOperand(0);
25411
25412   unsigned Opcode;
25413   if (!NegMul)
25414     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25415   else
25416     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25417
25418   return DAG.getNode(Opcode, dl, VT, A, B, C);
25419 }
25420
25421 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25422                                   TargetLowering::DAGCombinerInfo &DCI,
25423                                   const X86Subtarget *Subtarget) {
25424   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25425   //           (and (i32 x86isd::setcc_carry), 1)
25426   // This eliminates the zext. This transformation is necessary because
25427   // ISD::SETCC is always legalized to i8.
25428   SDLoc dl(N);
25429   SDValue N0 = N->getOperand(0);
25430   EVT VT = N->getValueType(0);
25431
25432   if (N0.getOpcode() == ISD::AND &&
25433       N0.hasOneUse() &&
25434       N0.getOperand(0).hasOneUse()) {
25435     SDValue N00 = N0.getOperand(0);
25436     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25437       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25438       if (!C || C->getZExtValue() != 1)
25439         return SDValue();
25440       return DAG.getNode(ISD::AND, dl, VT,
25441                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25442                                      N00.getOperand(0), N00.getOperand(1)),
25443                          DAG.getConstant(1, dl, VT));
25444     }
25445   }
25446
25447   if (N0.getOpcode() == ISD::TRUNCATE &&
25448       N0.hasOneUse() &&
25449       N0.getOperand(0).hasOneUse()) {
25450     SDValue N00 = N0.getOperand(0);
25451     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25452       return DAG.getNode(ISD::AND, dl, VT,
25453                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25454                                      N00.getOperand(0), N00.getOperand(1)),
25455                          DAG.getConstant(1, dl, VT));
25456     }
25457   }
25458
25459   if (VT.is256BitVector())
25460     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25461       return R;
25462
25463   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25464   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25465   // This exposes the zext to the udivrem lowering, so that it directly extends
25466   // from AH (which we otherwise need to do contortions to access).
25467   if (N0.getOpcode() == ISD::UDIVREM &&
25468       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25469       (VT == MVT::i32 || VT == MVT::i64)) {
25470     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25471     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25472                             N0.getOperand(0), N0.getOperand(1));
25473     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25474     return R.getValue(1);
25475   }
25476
25477   return SDValue();
25478 }
25479
25480 // Optimize x == -y --> x+y == 0
25481 //          x != -y --> x+y != 0
25482 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25483                                       const X86Subtarget* Subtarget) {
25484   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25485   SDValue LHS = N->getOperand(0);
25486   SDValue RHS = N->getOperand(1);
25487   EVT VT = N->getValueType(0);
25488   SDLoc DL(N);
25489
25490   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25491     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25492       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25493         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25494                                    LHS.getOperand(1));
25495         return DAG.getSetCC(DL, N->getValueType(0), addV,
25496                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25497       }
25498   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25499     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25500       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25501         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25502                                    RHS.getOperand(1));
25503         return DAG.getSetCC(DL, N->getValueType(0), addV,
25504                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25505       }
25506
25507   if (VT.getScalarType() == MVT::i1 &&
25508       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25509     bool IsSEXT0 =
25510         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25511         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25512     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25513
25514     if (!IsSEXT0 || !IsVZero1) {
25515       // Swap the operands and update the condition code.
25516       std::swap(LHS, RHS);
25517       CC = ISD::getSetCCSwappedOperands(CC);
25518
25519       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25520                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25521       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25522     }
25523
25524     if (IsSEXT0 && IsVZero1) {
25525       assert(VT == LHS.getOperand(0).getValueType() &&
25526              "Uexpected operand type");
25527       if (CC == ISD::SETGT)
25528         return DAG.getConstant(0, DL, VT);
25529       if (CC == ISD::SETLE)
25530         return DAG.getConstant(1, DL, VT);
25531       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25532         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25533
25534       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25535              "Unexpected condition code!");
25536       return LHS.getOperand(0);
25537     }
25538   }
25539
25540   return SDValue();
25541 }
25542
25543 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25544                                          SelectionDAG &DAG) {
25545   SDLoc dl(Load);
25546   MVT VT = Load->getSimpleValueType(0);
25547   MVT EVT = VT.getVectorElementType();
25548   SDValue Addr = Load->getOperand(1);
25549   SDValue NewAddr = DAG.getNode(
25550       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25551       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25552                       Addr.getSimpleValueType()));
25553
25554   SDValue NewLoad =
25555       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25556                   DAG.getMachineFunction().getMachineMemOperand(
25557                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25558   return NewLoad;
25559 }
25560
25561 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25562                                       const X86Subtarget *Subtarget) {
25563   SDLoc dl(N);
25564   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25565   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25566          "X86insertps is only defined for v4x32");
25567
25568   SDValue Ld = N->getOperand(1);
25569   if (MayFoldLoad(Ld)) {
25570     // Extract the countS bits from the immediate so we can get the proper
25571     // address when narrowing the vector load to a specific element.
25572     // When the second source op is a memory address, insertps doesn't use
25573     // countS and just gets an f32 from that address.
25574     unsigned DestIndex =
25575         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25576
25577     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25578
25579     // Create this as a scalar to vector to match the instruction pattern.
25580     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25581     // countS bits are ignored when loading from memory on insertps, which
25582     // means we don't need to explicitly set them to 0.
25583     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25584                        LoadScalarToVector, N->getOperand(2));
25585   }
25586   return SDValue();
25587 }
25588
25589 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25590   SDValue V0 = N->getOperand(0);
25591   SDValue V1 = N->getOperand(1);
25592   SDLoc DL(N);
25593   EVT VT = N->getValueType(0);
25594
25595   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25596   // operands and changing the mask to 1. This saves us a bunch of
25597   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25598   // x86InstrInfo knows how to commute this back after instruction selection
25599   // if it would help register allocation.
25600
25601   // TODO: If optimizing for size or a processor that doesn't suffer from
25602   // partial register update stalls, this should be transformed into a MOVSD
25603   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25604
25605   if (VT == MVT::v2f64)
25606     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25607       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25608         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25609         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25610       }
25611
25612   return SDValue();
25613 }
25614
25615 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25616 // as "sbb reg,reg", since it can be extended without zext and produces
25617 // an all-ones bit which is more useful than 0/1 in some cases.
25618 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25619                                MVT VT) {
25620   if (VT == MVT::i8)
25621     return DAG.getNode(ISD::AND, DL, VT,
25622                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25623                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25624                                    EFLAGS),
25625                        DAG.getConstant(1, DL, VT));
25626   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25627   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25628                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25629                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25630                                  EFLAGS));
25631 }
25632
25633 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25634 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25635                                    TargetLowering::DAGCombinerInfo &DCI,
25636                                    const X86Subtarget *Subtarget) {
25637   SDLoc DL(N);
25638   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25639   SDValue EFLAGS = N->getOperand(1);
25640
25641   if (CC == X86::COND_A) {
25642     // Try to convert COND_A into COND_B in an attempt to facilitate
25643     // materializing "setb reg".
25644     //
25645     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25646     // cannot take an immediate as its first operand.
25647     //
25648     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25649         EFLAGS.getValueType().isInteger() &&
25650         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25651       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25652                                    EFLAGS.getNode()->getVTList(),
25653                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25654       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25655       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25656     }
25657   }
25658
25659   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25660   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25661   // cases.
25662   if (CC == X86::COND_B)
25663     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25664
25665   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25666     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25667     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25668   }
25669
25670   return SDValue();
25671 }
25672
25673 // Optimize branch condition evaluation.
25674 //
25675 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25676                                     TargetLowering::DAGCombinerInfo &DCI,
25677                                     const X86Subtarget *Subtarget) {
25678   SDLoc DL(N);
25679   SDValue Chain = N->getOperand(0);
25680   SDValue Dest = N->getOperand(1);
25681   SDValue EFLAGS = N->getOperand(3);
25682   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25683
25684   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25685     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25686     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25687                        Flags);
25688   }
25689
25690   return SDValue();
25691 }
25692
25693 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25694                                                          SelectionDAG &DAG) {
25695   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25696   // optimize away operation when it's from a constant.
25697   //
25698   // The general transformation is:
25699   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25700   //       AND(VECTOR_CMP(x,y), constant2)
25701   //    constant2 = UNARYOP(constant)
25702
25703   // Early exit if this isn't a vector operation, the operand of the
25704   // unary operation isn't a bitwise AND, or if the sizes of the operations
25705   // aren't the same.
25706   EVT VT = N->getValueType(0);
25707   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25708       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25709       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25710     return SDValue();
25711
25712   // Now check that the other operand of the AND is a constant. We could
25713   // make the transformation for non-constant splats as well, but it's unclear
25714   // that would be a benefit as it would not eliminate any operations, just
25715   // perform one more step in scalar code before moving to the vector unit.
25716   if (BuildVectorSDNode *BV =
25717           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25718     // Bail out if the vector isn't a constant.
25719     if (!BV->isConstant())
25720       return SDValue();
25721
25722     // Everything checks out. Build up the new and improved node.
25723     SDLoc DL(N);
25724     EVT IntVT = BV->getValueType(0);
25725     // Create a new constant of the appropriate type for the transformed
25726     // DAG.
25727     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25728     // The AND node needs bitcasts to/from an integer vector type around it.
25729     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25730     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25731                                  N->getOperand(0)->getOperand(0), MaskConst);
25732     SDValue Res = DAG.getBitcast(VT, NewAnd);
25733     return Res;
25734   }
25735
25736   return SDValue();
25737 }
25738
25739 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25740                                         const X86Subtarget *Subtarget) {
25741   SDValue Op0 = N->getOperand(0);
25742   EVT VT = N->getValueType(0);
25743   EVT InVT = Op0.getValueType();
25744   EVT InSVT = InVT.getScalarType();
25745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25746
25747   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25748   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25749   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25750     SDLoc dl(N);
25751     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25752                                  InVT.getVectorNumElements());
25753     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25754
25755     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25756       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25757
25758     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25759   }
25760
25761   return SDValue();
25762 }
25763
25764 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25765                                         const X86Subtarget *Subtarget) {
25766   // First try to optimize away the conversion entirely when it's
25767   // conditionally from a constant. Vectors only.
25768   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25769     return Res;
25770
25771   // Now move on to more general possibilities.
25772   SDValue Op0 = N->getOperand(0);
25773   EVT VT = N->getValueType(0);
25774   EVT InVT = Op0.getValueType();
25775   EVT InSVT = InVT.getScalarType();
25776
25777   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25778   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25779   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25780     SDLoc dl(N);
25781     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25782                                  InVT.getVectorNumElements());
25783     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25784     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25785   }
25786
25787   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25788   // a 32-bit target where SSE doesn't support i64->FP operations.
25789   if (Op0.getOpcode() == ISD::LOAD) {
25790     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25791     EVT LdVT = Ld->getValueType(0);
25792
25793     // This transformation is not supported if the result type is f16
25794     if (VT == MVT::f16)
25795       return SDValue();
25796
25797     if (!Ld->isVolatile() && !VT.isVector() &&
25798         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25799         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25800       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25801           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25802       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25803       return FILDChain;
25804     }
25805   }
25806   return SDValue();
25807 }
25808
25809 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25810 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25811                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25812   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25813   // the result is either zero or one (depending on the input carry bit).
25814   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25815   if (X86::isZeroNode(N->getOperand(0)) &&
25816       X86::isZeroNode(N->getOperand(1)) &&
25817       // We don't have a good way to replace an EFLAGS use, so only do this when
25818       // dead right now.
25819       SDValue(N, 1).use_empty()) {
25820     SDLoc DL(N);
25821     EVT VT = N->getValueType(0);
25822     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25823     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25824                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25825                                            DAG.getConstant(X86::COND_B, DL,
25826                                                            MVT::i8),
25827                                            N->getOperand(2)),
25828                                DAG.getConstant(1, DL, VT));
25829     return DCI.CombineTo(N, Res1, CarryOut);
25830   }
25831
25832   return SDValue();
25833 }
25834
25835 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25836 //      (add Y, (setne X, 0)) -> sbb -1, Y
25837 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25838 //      (sub (setne X, 0), Y) -> adc -1, Y
25839 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25840   SDLoc DL(N);
25841
25842   // Look through ZExts.
25843   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25844   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25845     return SDValue();
25846
25847   SDValue SetCC = Ext.getOperand(0);
25848   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25849     return SDValue();
25850
25851   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25852   if (CC != X86::COND_E && CC != X86::COND_NE)
25853     return SDValue();
25854
25855   SDValue Cmp = SetCC.getOperand(1);
25856   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25857       !X86::isZeroNode(Cmp.getOperand(1)) ||
25858       !Cmp.getOperand(0).getValueType().isInteger())
25859     return SDValue();
25860
25861   SDValue CmpOp0 = Cmp.getOperand(0);
25862   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25863                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25864
25865   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25866   if (CC == X86::COND_NE)
25867     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25868                        DL, OtherVal.getValueType(), OtherVal,
25869                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25870                        NewCmp);
25871   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25872                      DL, OtherVal.getValueType(), OtherVal,
25873                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25874 }
25875
25876 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25877 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25878                                  const X86Subtarget *Subtarget) {
25879   EVT VT = N->getValueType(0);
25880   SDValue Op0 = N->getOperand(0);
25881   SDValue Op1 = N->getOperand(1);
25882
25883   // Try to synthesize horizontal adds from adds of shuffles.
25884   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25885        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25886       isHorizontalBinOp(Op0, Op1, true))
25887     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25888
25889   return OptimizeConditionalInDecrement(N, DAG);
25890 }
25891
25892 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25893                                  const X86Subtarget *Subtarget) {
25894   SDValue Op0 = N->getOperand(0);
25895   SDValue Op1 = N->getOperand(1);
25896
25897   // X86 can't encode an immediate LHS of a sub. See if we can push the
25898   // negation into a preceding instruction.
25899   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25900     // If the RHS of the sub is a XOR with one use and a constant, invert the
25901     // immediate. Then add one to the LHS of the sub so we can turn
25902     // X-Y -> X+~Y+1, saving one register.
25903     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25904         isa<ConstantSDNode>(Op1.getOperand(1))) {
25905       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25906       EVT VT = Op0.getValueType();
25907       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25908                                    Op1.getOperand(0),
25909                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25910       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25911                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25912     }
25913   }
25914
25915   // Try to synthesize horizontal adds from adds of shuffles.
25916   EVT VT = N->getValueType(0);
25917   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25918        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25919       isHorizontalBinOp(Op0, Op1, true))
25920     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25921
25922   return OptimizeConditionalInDecrement(N, DAG);
25923 }
25924
25925 /// performVZEXTCombine - Performs build vector combines
25926 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25927                                    TargetLowering::DAGCombinerInfo &DCI,
25928                                    const X86Subtarget *Subtarget) {
25929   SDLoc DL(N);
25930   MVT VT = N->getSimpleValueType(0);
25931   SDValue Op = N->getOperand(0);
25932   MVT OpVT = Op.getSimpleValueType();
25933   MVT OpEltVT = OpVT.getVectorElementType();
25934   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25935
25936   // (vzext (bitcast (vzext (x)) -> (vzext x)
25937   SDValue V = Op;
25938   while (V.getOpcode() == ISD::BITCAST)
25939     V = V.getOperand(0);
25940
25941   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25942     MVT InnerVT = V.getSimpleValueType();
25943     MVT InnerEltVT = InnerVT.getVectorElementType();
25944
25945     // If the element sizes match exactly, we can just do one larger vzext. This
25946     // is always an exact type match as vzext operates on integer types.
25947     if (OpEltVT == InnerEltVT) {
25948       assert(OpVT == InnerVT && "Types must match for vzext!");
25949       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25950     }
25951
25952     // The only other way we can combine them is if only a single element of the
25953     // inner vzext is used in the input to the outer vzext.
25954     if (InnerEltVT.getSizeInBits() < InputBits)
25955       return SDValue();
25956
25957     // In this case, the inner vzext is completely dead because we're going to
25958     // only look at bits inside of the low element. Just do the outer vzext on
25959     // a bitcast of the input to the inner.
25960     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25961   }
25962
25963   // Check if we can bypass extracting and re-inserting an element of an input
25964   // vector. Essentially:
25965   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25966   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25967       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25968       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25969     SDValue ExtractedV = V.getOperand(0);
25970     SDValue OrigV = ExtractedV.getOperand(0);
25971     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25972       if (ExtractIdx->getZExtValue() == 0) {
25973         MVT OrigVT = OrigV.getSimpleValueType();
25974         // Extract a subvector if necessary...
25975         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25976           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25977           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25978                                     OrigVT.getVectorNumElements() / Ratio);
25979           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25980                               DAG.getIntPtrConstant(0, DL));
25981         }
25982         Op = DAG.getBitcast(OpVT, OrigV);
25983         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25984       }
25985   }
25986
25987   return SDValue();
25988 }
25989
25990 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25991                                              DAGCombinerInfo &DCI) const {
25992   SelectionDAG &DAG = DCI.DAG;
25993   switch (N->getOpcode()) {
25994   default: break;
25995   case ISD::EXTRACT_VECTOR_ELT:
25996     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25997   case ISD::VSELECT:
25998   case ISD::SELECT:
25999   case X86ISD::SHRUNKBLEND:
26000     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26001   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26002   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26003   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26004   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26005   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26006   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26007   case ISD::SHL:
26008   case ISD::SRA:
26009   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26010   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26011   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26012   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26013   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26014   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26015   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26016   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26017   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26018   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26019   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26020   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26021   case X86ISD::FXOR:
26022   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
26023   case X86ISD::FMIN:
26024   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26025   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26026   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26027   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26028   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26029   case ISD::ANY_EXTEND:
26030   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26031   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26032   case ISD::SIGN_EXTEND_INREG:
26033     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26034   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26035   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26036   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26037   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26038   case X86ISD::SHUFP:       // Handle all target specific shuffles
26039   case X86ISD::PALIGNR:
26040   case X86ISD::UNPCKH:
26041   case X86ISD::UNPCKL:
26042   case X86ISD::MOVHLPS:
26043   case X86ISD::MOVLHPS:
26044   case X86ISD::PSHUFB:
26045   case X86ISD::PSHUFD:
26046   case X86ISD::PSHUFHW:
26047   case X86ISD::PSHUFLW:
26048   case X86ISD::MOVSS:
26049   case X86ISD::MOVSD:
26050   case X86ISD::VPERMILPI:
26051   case X86ISD::VPERM2X128:
26052   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26053   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26054   case X86ISD::INSERTPS: {
26055     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26056       return PerformINSERTPSCombine(N, DAG, Subtarget);
26057     break;
26058   }
26059   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26060   }
26061
26062   return SDValue();
26063 }
26064
26065 /// isTypeDesirableForOp - Return true if the target has native support for
26066 /// the specified value type and it is 'desirable' to use the type for the
26067 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26068 /// instruction encodings are longer and some i16 instructions are slow.
26069 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26070   if (!isTypeLegal(VT))
26071     return false;
26072   if (VT != MVT::i16)
26073     return true;
26074
26075   switch (Opc) {
26076   default:
26077     return true;
26078   case ISD::LOAD:
26079   case ISD::SIGN_EXTEND:
26080   case ISD::ZERO_EXTEND:
26081   case ISD::ANY_EXTEND:
26082   case ISD::SHL:
26083   case ISD::SRL:
26084   case ISD::SUB:
26085   case ISD::ADD:
26086   case ISD::MUL:
26087   case ISD::AND:
26088   case ISD::OR:
26089   case ISD::XOR:
26090     return false;
26091   }
26092 }
26093
26094 /// IsDesirableToPromoteOp - This method query the target whether it is
26095 /// beneficial for dag combiner to promote the specified node. If true, it
26096 /// should return the desired promotion type by reference.
26097 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26098   EVT VT = Op.getValueType();
26099   if (VT != MVT::i16)
26100     return false;
26101
26102   bool Promote = false;
26103   bool Commute = false;
26104   switch (Op.getOpcode()) {
26105   default: break;
26106   case ISD::LOAD: {
26107     LoadSDNode *LD = cast<LoadSDNode>(Op);
26108     // If the non-extending load has a single use and it's not live out, then it
26109     // might be folded.
26110     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26111                                                      Op.hasOneUse()*/) {
26112       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26113              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26114         // The only case where we'd want to promote LOAD (rather then it being
26115         // promoted as an operand is when it's only use is liveout.
26116         if (UI->getOpcode() != ISD::CopyToReg)
26117           return false;
26118       }
26119     }
26120     Promote = true;
26121     break;
26122   }
26123   case ISD::SIGN_EXTEND:
26124   case ISD::ZERO_EXTEND:
26125   case ISD::ANY_EXTEND:
26126     Promote = true;
26127     break;
26128   case ISD::SHL:
26129   case ISD::SRL: {
26130     SDValue N0 = Op.getOperand(0);
26131     // Look out for (store (shl (load), x)).
26132     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26133       return false;
26134     Promote = true;
26135     break;
26136   }
26137   case ISD::ADD:
26138   case ISD::MUL:
26139   case ISD::AND:
26140   case ISD::OR:
26141   case ISD::XOR:
26142     Commute = true;
26143     // fallthrough
26144   case ISD::SUB: {
26145     SDValue N0 = Op.getOperand(0);
26146     SDValue N1 = Op.getOperand(1);
26147     if (!Commute && MayFoldLoad(N1))
26148       return false;
26149     // Avoid disabling potential load folding opportunities.
26150     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26151       return false;
26152     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26153       return false;
26154     Promote = true;
26155   }
26156   }
26157
26158   PVT = MVT::i32;
26159   return Promote;
26160 }
26161
26162 //===----------------------------------------------------------------------===//
26163 //                           X86 Inline Assembly Support
26164 //===----------------------------------------------------------------------===//
26165
26166 // Helper to match a string separated by whitespace.
26167 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26168   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26169
26170   for (StringRef Piece : Pieces) {
26171     if (!S.startswith(Piece)) // Check if the piece matches.
26172       return false;
26173
26174     S = S.substr(Piece.size());
26175     StringRef::size_type Pos = S.find_first_not_of(" \t");
26176     if (Pos == 0) // We matched a prefix.
26177       return false;
26178
26179     S = S.substr(Pos);
26180   }
26181
26182   return S.empty();
26183 }
26184
26185 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26186
26187   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26188     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26189         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26190         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26191
26192       if (AsmPieces.size() == 3)
26193         return true;
26194       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26195         return true;
26196     }
26197   }
26198   return false;
26199 }
26200
26201 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26202   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26203
26204   std::string AsmStr = IA->getAsmString();
26205
26206   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26207   if (!Ty || Ty->getBitWidth() % 16 != 0)
26208     return false;
26209
26210   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26211   SmallVector<StringRef, 4> AsmPieces;
26212   SplitString(AsmStr, AsmPieces, ";\n");
26213
26214   switch (AsmPieces.size()) {
26215   default: return false;
26216   case 1:
26217     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26218     // we will turn this bswap into something that will be lowered to logical
26219     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26220     // lower so don't worry about this.
26221     // bswap $0
26222     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26223         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26224         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26225         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26226         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26227         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26228       // No need to check constraints, nothing other than the equivalent of
26229       // "=r,0" would be valid here.
26230       return IntrinsicLowering::LowerToByteSwap(CI);
26231     }
26232
26233     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26234     if (CI->getType()->isIntegerTy(16) &&
26235         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26236         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26237          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26238       AsmPieces.clear();
26239       StringRef ConstraintsStr = IA->getConstraintString();
26240       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26241       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26242       if (clobbersFlagRegisters(AsmPieces))
26243         return IntrinsicLowering::LowerToByteSwap(CI);
26244     }
26245     break;
26246   case 3:
26247     if (CI->getType()->isIntegerTy(32) &&
26248         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26249         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26250         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26251         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26252       AsmPieces.clear();
26253       StringRef ConstraintsStr = IA->getConstraintString();
26254       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26255       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26256       if (clobbersFlagRegisters(AsmPieces))
26257         return IntrinsicLowering::LowerToByteSwap(CI);
26258     }
26259
26260     if (CI->getType()->isIntegerTy(64)) {
26261       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26262       if (Constraints.size() >= 2 &&
26263           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26264           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26265         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26266         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26267             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26268             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26269           return IntrinsicLowering::LowerToByteSwap(CI);
26270       }
26271     }
26272     break;
26273   }
26274   return false;
26275 }
26276
26277 /// getConstraintType - Given a constraint letter, return the type of
26278 /// constraint it is for this target.
26279 X86TargetLowering::ConstraintType
26280 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26281   if (Constraint.size() == 1) {
26282     switch (Constraint[0]) {
26283     case 'R':
26284     case 'q':
26285     case 'Q':
26286     case 'f':
26287     case 't':
26288     case 'u':
26289     case 'y':
26290     case 'x':
26291     case 'Y':
26292     case 'l':
26293       return C_RegisterClass;
26294     case 'a':
26295     case 'b':
26296     case 'c':
26297     case 'd':
26298     case 'S':
26299     case 'D':
26300     case 'A':
26301       return C_Register;
26302     case 'I':
26303     case 'J':
26304     case 'K':
26305     case 'L':
26306     case 'M':
26307     case 'N':
26308     case 'G':
26309     case 'C':
26310     case 'e':
26311     case 'Z':
26312       return C_Other;
26313     default:
26314       break;
26315     }
26316   }
26317   return TargetLowering::getConstraintType(Constraint);
26318 }
26319
26320 /// Examine constraint type and operand type and determine a weight value.
26321 /// This object must already have been set up with the operand type
26322 /// and the current alternative constraint selected.
26323 TargetLowering::ConstraintWeight
26324   X86TargetLowering::getSingleConstraintMatchWeight(
26325     AsmOperandInfo &info, const char *constraint) const {
26326   ConstraintWeight weight = CW_Invalid;
26327   Value *CallOperandVal = info.CallOperandVal;
26328     // If we don't have a value, we can't do a match,
26329     // but allow it at the lowest weight.
26330   if (!CallOperandVal)
26331     return CW_Default;
26332   Type *type = CallOperandVal->getType();
26333   // Look at the constraint type.
26334   switch (*constraint) {
26335   default:
26336     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26337   case 'R':
26338   case 'q':
26339   case 'Q':
26340   case 'a':
26341   case 'b':
26342   case 'c':
26343   case 'd':
26344   case 'S':
26345   case 'D':
26346   case 'A':
26347     if (CallOperandVal->getType()->isIntegerTy())
26348       weight = CW_SpecificReg;
26349     break;
26350   case 'f':
26351   case 't':
26352   case 'u':
26353     if (type->isFloatingPointTy())
26354       weight = CW_SpecificReg;
26355     break;
26356   case 'y':
26357     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26358       weight = CW_SpecificReg;
26359     break;
26360   case 'x':
26361   case 'Y':
26362     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26363         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26364       weight = CW_Register;
26365     break;
26366   case 'I':
26367     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26368       if (C->getZExtValue() <= 31)
26369         weight = CW_Constant;
26370     }
26371     break;
26372   case 'J':
26373     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26374       if (C->getZExtValue() <= 63)
26375         weight = CW_Constant;
26376     }
26377     break;
26378   case 'K':
26379     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26380       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26381         weight = CW_Constant;
26382     }
26383     break;
26384   case 'L':
26385     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26386       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26387         weight = CW_Constant;
26388     }
26389     break;
26390   case 'M':
26391     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26392       if (C->getZExtValue() <= 3)
26393         weight = CW_Constant;
26394     }
26395     break;
26396   case 'N':
26397     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26398       if (C->getZExtValue() <= 0xff)
26399         weight = CW_Constant;
26400     }
26401     break;
26402   case 'G':
26403   case 'C':
26404     if (isa<ConstantFP>(CallOperandVal)) {
26405       weight = CW_Constant;
26406     }
26407     break;
26408   case 'e':
26409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26410       if ((C->getSExtValue() >= -0x80000000LL) &&
26411           (C->getSExtValue() <= 0x7fffffffLL))
26412         weight = CW_Constant;
26413     }
26414     break;
26415   case 'Z':
26416     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26417       if (C->getZExtValue() <= 0xffffffff)
26418         weight = CW_Constant;
26419     }
26420     break;
26421   }
26422   return weight;
26423 }
26424
26425 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26426 /// with another that has more specific requirements based on the type of the
26427 /// corresponding operand.
26428 const char *X86TargetLowering::
26429 LowerXConstraint(EVT ConstraintVT) const {
26430   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26431   // 'f' like normal targets.
26432   if (ConstraintVT.isFloatingPoint()) {
26433     if (Subtarget->hasSSE2())
26434       return "Y";
26435     if (Subtarget->hasSSE1())
26436       return "x";
26437   }
26438
26439   return TargetLowering::LowerXConstraint(ConstraintVT);
26440 }
26441
26442 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26443 /// vector.  If it is invalid, don't add anything to Ops.
26444 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26445                                                      std::string &Constraint,
26446                                                      std::vector<SDValue>&Ops,
26447                                                      SelectionDAG &DAG) const {
26448   SDValue Result;
26449
26450   // Only support length 1 constraints for now.
26451   if (Constraint.length() > 1) return;
26452
26453   char ConstraintLetter = Constraint[0];
26454   switch (ConstraintLetter) {
26455   default: break;
26456   case 'I':
26457     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26458       if (C->getZExtValue() <= 31) {
26459         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26460                                        Op.getValueType());
26461         break;
26462       }
26463     }
26464     return;
26465   case 'J':
26466     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26467       if (C->getZExtValue() <= 63) {
26468         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26469                                        Op.getValueType());
26470         break;
26471       }
26472     }
26473     return;
26474   case 'K':
26475     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26476       if (isInt<8>(C->getSExtValue())) {
26477         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26478                                        Op.getValueType());
26479         break;
26480       }
26481     }
26482     return;
26483   case 'L':
26484     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26485       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26486           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26487         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26488                                        Op.getValueType());
26489         break;
26490       }
26491     }
26492     return;
26493   case 'M':
26494     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26495       if (C->getZExtValue() <= 3) {
26496         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26497                                        Op.getValueType());
26498         break;
26499       }
26500     }
26501     return;
26502   case 'N':
26503     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26504       if (C->getZExtValue() <= 255) {
26505         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26506                                        Op.getValueType());
26507         break;
26508       }
26509     }
26510     return;
26511   case 'O':
26512     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26513       if (C->getZExtValue() <= 127) {
26514         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26515                                        Op.getValueType());
26516         break;
26517       }
26518     }
26519     return;
26520   case 'e': {
26521     // 32-bit signed value
26522     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26523       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26524                                            C->getSExtValue())) {
26525         // Widen to 64 bits here to get it sign extended.
26526         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26527         break;
26528       }
26529     // FIXME gcc accepts some relocatable values here too, but only in certain
26530     // memory models; it's complicated.
26531     }
26532     return;
26533   }
26534   case 'Z': {
26535     // 32-bit unsigned value
26536     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26537       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26538                                            C->getZExtValue())) {
26539         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26540                                        Op.getValueType());
26541         break;
26542       }
26543     }
26544     // FIXME gcc accepts some relocatable values here too, but only in certain
26545     // memory models; it's complicated.
26546     return;
26547   }
26548   case 'i': {
26549     // Literal immediates are always ok.
26550     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26551       // Widen to 64 bits here to get it sign extended.
26552       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26553       break;
26554     }
26555
26556     // In any sort of PIC mode addresses need to be computed at runtime by
26557     // adding in a register or some sort of table lookup.  These can't
26558     // be used as immediates.
26559     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26560       return;
26561
26562     // If we are in non-pic codegen mode, we allow the address of a global (with
26563     // an optional displacement) to be used with 'i'.
26564     GlobalAddressSDNode *GA = nullptr;
26565     int64_t Offset = 0;
26566
26567     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26568     while (1) {
26569       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26570         Offset += GA->getOffset();
26571         break;
26572       } else if (Op.getOpcode() == ISD::ADD) {
26573         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26574           Offset += C->getZExtValue();
26575           Op = Op.getOperand(0);
26576           continue;
26577         }
26578       } else if (Op.getOpcode() == ISD::SUB) {
26579         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26580           Offset += -C->getZExtValue();
26581           Op = Op.getOperand(0);
26582           continue;
26583         }
26584       }
26585
26586       // Otherwise, this isn't something we can handle, reject it.
26587       return;
26588     }
26589
26590     const GlobalValue *GV = GA->getGlobal();
26591     // If we require an extra load to get this address, as in PIC mode, we
26592     // can't accept it.
26593     if (isGlobalStubReference(
26594             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26595       return;
26596
26597     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26598                                         GA->getValueType(0), Offset);
26599     break;
26600   }
26601   }
26602
26603   if (Result.getNode()) {
26604     Ops.push_back(Result);
26605     return;
26606   }
26607   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26608 }
26609
26610 std::pair<unsigned, const TargetRegisterClass *>
26611 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26612                                                 StringRef Constraint,
26613                                                 MVT VT) const {
26614   // First, see if this is a constraint that directly corresponds to an LLVM
26615   // register class.
26616   if (Constraint.size() == 1) {
26617     // GCC Constraint Letters
26618     switch (Constraint[0]) {
26619     default: break;
26620       // TODO: Slight differences here in allocation order and leaving
26621       // RIP in the class. Do they matter any more here than they do
26622       // in the normal allocation?
26623     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26624       if (Subtarget->is64Bit()) {
26625         if (VT == MVT::i32 || VT == MVT::f32)
26626           return std::make_pair(0U, &X86::GR32RegClass);
26627         if (VT == MVT::i16)
26628           return std::make_pair(0U, &X86::GR16RegClass);
26629         if (VT == MVT::i8 || VT == MVT::i1)
26630           return std::make_pair(0U, &X86::GR8RegClass);
26631         if (VT == MVT::i64 || VT == MVT::f64)
26632           return std::make_pair(0U, &X86::GR64RegClass);
26633         break;
26634       }
26635       // 32-bit fallthrough
26636     case 'Q':   // Q_REGS
26637       if (VT == MVT::i32 || VT == MVT::f32)
26638         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26639       if (VT == MVT::i16)
26640         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26641       if (VT == MVT::i8 || VT == MVT::i1)
26642         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26643       if (VT == MVT::i64)
26644         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26645       break;
26646     case 'r':   // GENERAL_REGS
26647     case 'l':   // INDEX_REGS
26648       if (VT == MVT::i8 || VT == MVT::i1)
26649         return std::make_pair(0U, &X86::GR8RegClass);
26650       if (VT == MVT::i16)
26651         return std::make_pair(0U, &X86::GR16RegClass);
26652       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26653         return std::make_pair(0U, &X86::GR32RegClass);
26654       return std::make_pair(0U, &X86::GR64RegClass);
26655     case 'R':   // LEGACY_REGS
26656       if (VT == MVT::i8 || VT == MVT::i1)
26657         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26658       if (VT == MVT::i16)
26659         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26660       if (VT == MVT::i32 || !Subtarget->is64Bit())
26661         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26662       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26663     case 'f':  // FP Stack registers.
26664       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26665       // value to the correct fpstack register class.
26666       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26667         return std::make_pair(0U, &X86::RFP32RegClass);
26668       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26669         return std::make_pair(0U, &X86::RFP64RegClass);
26670       return std::make_pair(0U, &X86::RFP80RegClass);
26671     case 'y':   // MMX_REGS if MMX allowed.
26672       if (!Subtarget->hasMMX()) break;
26673       return std::make_pair(0U, &X86::VR64RegClass);
26674     case 'Y':   // SSE_REGS if SSE2 allowed
26675       if (!Subtarget->hasSSE2()) break;
26676       // FALL THROUGH.
26677     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26678       if (!Subtarget->hasSSE1()) break;
26679
26680       switch (VT.SimpleTy) {
26681       default: break;
26682       // Scalar SSE types.
26683       case MVT::f32:
26684       case MVT::i32:
26685         return std::make_pair(0U, &X86::FR32RegClass);
26686       case MVT::f64:
26687       case MVT::i64:
26688         return std::make_pair(0U, &X86::FR64RegClass);
26689       // Vector types.
26690       case MVT::v16i8:
26691       case MVT::v8i16:
26692       case MVT::v4i32:
26693       case MVT::v2i64:
26694       case MVT::v4f32:
26695       case MVT::v2f64:
26696         return std::make_pair(0U, &X86::VR128RegClass);
26697       // AVX types.
26698       case MVT::v32i8:
26699       case MVT::v16i16:
26700       case MVT::v8i32:
26701       case MVT::v4i64:
26702       case MVT::v8f32:
26703       case MVT::v4f64:
26704         return std::make_pair(0U, &X86::VR256RegClass);
26705       case MVT::v8f64:
26706       case MVT::v16f32:
26707       case MVT::v16i32:
26708       case MVT::v8i64:
26709         return std::make_pair(0U, &X86::VR512RegClass);
26710       }
26711       break;
26712     }
26713   }
26714
26715   // Use the default implementation in TargetLowering to convert the register
26716   // constraint into a member of a register class.
26717   std::pair<unsigned, const TargetRegisterClass*> Res;
26718   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26719
26720   // Not found as a standard register?
26721   if (!Res.second) {
26722     // Map st(0) -> st(7) -> ST0
26723     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26724         tolower(Constraint[1]) == 's' &&
26725         tolower(Constraint[2]) == 't' &&
26726         Constraint[3] == '(' &&
26727         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26728         Constraint[5] == ')' &&
26729         Constraint[6] == '}') {
26730
26731       Res.first = X86::FP0+Constraint[4]-'0';
26732       Res.second = &X86::RFP80RegClass;
26733       return Res;
26734     }
26735
26736     // GCC allows "st(0)" to be called just plain "st".
26737     if (StringRef("{st}").equals_lower(Constraint)) {
26738       Res.first = X86::FP0;
26739       Res.second = &X86::RFP80RegClass;
26740       return Res;
26741     }
26742
26743     // flags -> EFLAGS
26744     if (StringRef("{flags}").equals_lower(Constraint)) {
26745       Res.first = X86::EFLAGS;
26746       Res.second = &X86::CCRRegClass;
26747       return Res;
26748     }
26749
26750     // 'A' means EAX + EDX.
26751     if (Constraint == "A") {
26752       Res.first = X86::EAX;
26753       Res.second = &X86::GR32_ADRegClass;
26754       return Res;
26755     }
26756     return Res;
26757   }
26758
26759   // Otherwise, check to see if this is a register class of the wrong value
26760   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26761   // turn into {ax},{dx}.
26762   // MVT::Other is used to specify clobber names.
26763   if (Res.second->hasType(VT) || VT == MVT::Other)
26764     return Res;   // Correct type already, nothing to do.
26765
26766   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26767   // return "eax". This should even work for things like getting 64bit integer
26768   // registers when given an f64 type.
26769   const TargetRegisterClass *Class = Res.second;
26770   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26771       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26772     unsigned Size = VT.getSizeInBits();
26773     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26774                                   : Size == 16 ? MVT::i16
26775                                   : Size == 32 ? MVT::i32
26776                                   : Size == 64 ? MVT::i64
26777                                   : MVT::Other;
26778     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26779     if (DestReg > 0) {
26780       Res.first = DestReg;
26781       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26782                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26783                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26784                  : &X86::GR64RegClass;
26785       assert(Res.second->contains(Res.first) && "Register in register class");
26786     } else {
26787       // No register found/type mismatch.
26788       Res.first = 0;
26789       Res.second = nullptr;
26790     }
26791   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26792              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26793              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26794              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26795              Class == &X86::VR512RegClass) {
26796     // Handle references to XMM physical registers that got mapped into the
26797     // wrong class.  This can happen with constraints like {xmm0} where the
26798     // target independent register mapper will just pick the first match it can
26799     // find, ignoring the required type.
26800
26801     if (VT == MVT::f32 || VT == MVT::i32)
26802       Res.second = &X86::FR32RegClass;
26803     else if (VT == MVT::f64 || VT == MVT::i64)
26804       Res.second = &X86::FR64RegClass;
26805     else if (X86::VR128RegClass.hasType(VT))
26806       Res.second = &X86::VR128RegClass;
26807     else if (X86::VR256RegClass.hasType(VT))
26808       Res.second = &X86::VR256RegClass;
26809     else if (X86::VR512RegClass.hasType(VT))
26810       Res.second = &X86::VR512RegClass;
26811     else {
26812       // Type mismatch and not a clobber: Return an error;
26813       Res.first = 0;
26814       Res.second = nullptr;
26815     }
26816   }
26817
26818   return Res;
26819 }
26820
26821 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26822                                             const AddrMode &AM, Type *Ty,
26823                                             unsigned AS) const {
26824   // Scaling factors are not free at all.
26825   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26826   // will take 2 allocations in the out of order engine instead of 1
26827   // for plain addressing mode, i.e. inst (reg1).
26828   // E.g.,
26829   // vaddps (%rsi,%drx), %ymm0, %ymm1
26830   // Requires two allocations (one for the load, one for the computation)
26831   // whereas:
26832   // vaddps (%rsi), %ymm0, %ymm1
26833   // Requires just 1 allocation, i.e., freeing allocations for other operations
26834   // and having less micro operations to execute.
26835   //
26836   // For some X86 architectures, this is even worse because for instance for
26837   // stores, the complex addressing mode forces the instruction to use the
26838   // "load" ports instead of the dedicated "store" port.
26839   // E.g., on Haswell:
26840   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26841   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26842   if (isLegalAddressingMode(DL, AM, Ty, AS))
26843     // Scale represents reg2 * scale, thus account for 1
26844     // as soon as we use a second register.
26845     return AM.Scale != 0;
26846   return -1;
26847 }
26848
26849 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26850   // Integer division on x86 is expensive. However, when aggressively optimizing
26851   // for code size, we prefer to use a div instruction, as it is usually smaller
26852   // than the alternative sequence.
26853   // The exception to this is vector division. Since x86 doesn't have vector
26854   // integer division, leaving the division as-is is a loss even in terms of
26855   // size, because it will have to be scalarized, while the alternative code
26856   // sequence can be performed in vector form.
26857   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26858                                    Attribute::MinSize);
26859   return OptSize && !VT.isVector();
26860 }