[X86][AVX512CD] add mask broadcast intrinsics
[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/Analysis/LibCallSemantics.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/WinEHFuncInfo.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCSymbol.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "X86IntrinsicsInfo.h"
56 #include <bitset>
57 #include <numeric>
58 #include <cctype>
59 using namespace llvm;
60
61 #define DEBUG_TYPE "x86-isel"
62
63 STATISTIC(NumTailCalls, "Number of tail calls");
64
65 static cl::opt<bool> ExperimentalVectorWideningLegalization(
66     "x86-experimental-vector-widening-legalization", cl::init(false),
67     cl::desc("Enable an experimental vector type legalization through widening "
68              "rather than promotion."),
69     cl::Hidden);
70
71 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
72                                      const X86Subtarget &STI)
73     : TargetLowering(TM), Subtarget(&STI) {
74   X86ScalarSSEf64 = Subtarget->hasSSE2();
75   X86ScalarSSEf32 = Subtarget->hasSSE1();
76   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77
78   // Set up the TargetLowering object.
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     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168       // f32/f64 are legal, f80 is custom.
169       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
170     else
171       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173   } else if (!Subtarget->useSoftFloat()) {
174     // We have an algorithm for SSE2->double, and we turn this into a
175     // 64-bit FILD followed by conditional FADD for other targets.
176     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
177     // We have an algorithm for SSE2, and we turn this into a 64-bit
178     // FILD or VCVTUSI2SS/SD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
180   }
181
182   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
186
187   if (!Subtarget->useSoftFloat()) {
188     // SSE has no i16 to fp conversion, only i32
189     if (X86ScalarSSEf32) {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
191       // f32 and f64 cases are Legal, f80 case is not
192       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
193     } else {
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     }
197   } else {
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
200   }
201
202   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
203   // this operation.
204   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
206
207   if (!Subtarget->useSoftFloat()) {
208     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
209     // are Legal, f80 is custom lowered.
210     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
212
213     if (X86ScalarSSEf32) {
214       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
215       // f32 and f64 cases are Legal, f80 case is not
216       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
217     } else {
218       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
220     }
221   } else {
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
225   }
226
227   // Handle FP_TO_UINT by promoting the destination to a larger signed
228   // conversion.
229   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
232
233   if (Subtarget->is64Bit()) {
234     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
235       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
236       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
238     } else {
239       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
241     }
242   } else if (!Subtarget->useSoftFloat()) {
243     // Since AVX is a superset of SSE3, only check for SSE here.
244     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
245       // Expand FP_TO_UINT into a select.
246       // FIXME: We would like to use a Custom expander here eventually to do
247       // the optimal thing for SSE vs. the default expansion in the legalizer.
248       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
249     else
250       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254
255     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
256   }
257
258   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
259   if (!X86ScalarSSEf64) {
260     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
261     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
262     if (Subtarget->is64Bit()) {
263       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
264       // Without SSE, i64->f64 goes through memory.
265       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
266     }
267   }
268
269   // Scalar integer divide and remainder are lowered to use operations that
270   // produce two results, to match the available instructions. This exposes
271   // the two-result form to trivial CSE, which is able to combine x/y and x%y
272   // into a single instruction.
273   //
274   // Scalar integer multiply-high is also lowered to use two-result
275   // operations, to match the available instructions. However, plain multiply
276   // (low) operations are left as Legal, as there are single-result
277   // instructions for this in x86. Using the two-result multiply instructions
278   // when both high and low results are needed must be arranged by dagcombine.
279   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
280     setOperationAction(ISD::MULHS, VT, Expand);
281     setOperationAction(ISD::MULHU, VT, Expand);
282     setOperationAction(ISD::SDIV, VT, Expand);
283     setOperationAction(ISD::UDIV, VT, Expand);
284     setOperationAction(ISD::SREM, VT, Expand);
285     setOperationAction(ISD::UREM, VT, Expand);
286
287     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
288     setOperationAction(ISD::ADDC, VT, Custom);
289     setOperationAction(ISD::ADDE, VT, Custom);
290     setOperationAction(ISD::SUBC, VT, Custom);
291     setOperationAction(ISD::SUBE, VT, Custom);
292   }
293
294   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
295   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
296   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
310   if (Subtarget->is64Bit())
311     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
314   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
315   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
316
317   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
318     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
319     // is. We should promote the value to 64-bits to solve this.
320     // This is what the CRT headers do - `fmodf` is an inline header
321     // function casting to f64 and calling `fmod`.
322     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
323   } else {
324     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
325   }
326
327   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
328   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
329   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
330
331   // Promote the i8 variants and force them on up to i32 which has a shorter
332   // encoding.
333   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
334   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
335   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
336   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
337   if (Subtarget->hasBMI()) {
338     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
339     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
342   } else {
343     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
344     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
345     if (Subtarget->is64Bit())
346       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
347   }
348
349   if (Subtarget->hasLZCNT()) {
350     // When promoting the i8 variants, force them to i32 for a shorter
351     // encoding.
352     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
353     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
355     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
358     if (Subtarget->is64Bit())
359       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
360   } else {
361     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
362     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
363     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
364     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
365     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
366     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
367     if (Subtarget->is64Bit()) {
368       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
369       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
370     }
371   }
372
373   // Special handling for half-precision floating point conversions.
374   // If we don't have F16C support, then lower half float conversions
375   // into library calls.
376   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
377     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
378     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
379   }
380
381   // There's never any support for operations beyond MVT::f32.
382   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
383   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
384   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
385   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
386
387   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
388   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
389   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
390   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
391   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
392   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
393
394   if (Subtarget->hasPOPCNT()) {
395     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
396   } else {
397     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
398     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
399     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
400     if (Subtarget->is64Bit())
401       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
402   }
403
404   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
405
406   if (!Subtarget->hasMOVBE())
407     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
408
409   // These should be promoted to a larger select which is supported.
410   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
411   // X86 wants to expand cmov itself.
412   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
413   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
414   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
415   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
416   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
419   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
420   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
421   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
422   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
424   if (Subtarget->is64Bit()) {
425     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
426     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
427   }
428   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
429   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
430   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
431   // support continuation, user-level threading, and etc.. As a result, no
432   // other SjLj exception interfaces are implemented and please don't build
433   // your own exception handling based on them.
434   // LLVM/Clang supports zero-cost DWARF exception handling.
435   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
436   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
437
438   // Darwin ABI issue.
439   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
440   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
441   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
442   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
443   if (Subtarget->is64Bit())
444     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
445   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
446   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
449     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
450     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
451     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
452     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
453   }
454   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
455   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
456   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
457   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
458   if (Subtarget->is64Bit()) {
459     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
460     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
461     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
462   }
463
464   if (Subtarget->hasSSE1())
465     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
466
467   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
468
469   // Expand certain atomics
470   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
471     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
472     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
473     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
474   }
475
476   if (Subtarget->hasCmpxchg16b()) {
477     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
478   }
479
480   // FIXME - use subtarget debug flags
481   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
482       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
483     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
484   }
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     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
852     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
853     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
854     // ISD::CTTZ v2i64 - scalarization is faster.
855     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
856     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
857     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
858     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
859
860     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
861     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
900       setOperationAction(ISD::AND,    VT, Promote);
901       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
902       setOperationAction(ISD::OR,     VT, Promote);
903       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
904       setOperationAction(ISD::XOR,    VT, Promote);
905       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
906       setOperationAction(ISD::LOAD,   VT, Promote);
907       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
908       setOperationAction(ISD::SELECT, VT, Promote);
909       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
910     }
911
912     // Custom lower v2i64 and v2f64 selects.
913     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
914     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
915     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
916     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
917
918     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
920
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
922
923     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
924     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
925     // As there is no 64-bit GPR available, we need build a special custom
926     // sequence to convert from v2i32 to v2f32.
927     if (!Subtarget->is64Bit())
928       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
929
930     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
931     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
932
933     for (MVT VT : MVT::fp_vector_valuetypes())
934       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
935
936     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
937     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
938     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
939   }
940
941   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
942     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
943       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
944       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
945       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
946       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
947       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
948     }
949
950     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
951     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
952     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
953     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
958
959     // FIXME: Do we need to handle scalar-to-vector here?
960     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
961
962     // We directly match byte blends in the backend as they match the VSELECT
963     // condition form.
964     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
965
966     // SSE41 brings specific instructions for doing vector sign extend even in
967     // cases where we don't have SRA.
968     for (MVT VT : MVT::integer_vector_valuetypes()) {
969       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
970       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
972     }
973
974     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
976     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
981
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
983     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
988
989     // i8 and i16 vectors are custom because the source register and source
990     // source memory operand types are not the same width.  f32 vectors are
991     // custom since the immediate controlling the insert encodes additional
992     // information.
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
997
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1002
1003     // FIXME: these should be Legal, but that's only for the case where
1004     // the index is constant.  For now custom expand to deal with that.
1005     if (Subtarget->is64Bit()) {
1006       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1007       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1008     }
1009   }
1010
1011   if (Subtarget->hasSSE2()) {
1012     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1013     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1015
1016     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1017     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1018
1019     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1020     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1021
1022     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1023     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1024
1025     // In the customized shift lowering, the legal cases in AVX2 will be
1026     // recognized.
1027     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1028     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1029
1030     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1031     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1032
1033     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1034     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1035   }
1036
1037   if (Subtarget->hasXOP()) {
1038     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1039     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1040     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1041     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1042     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1043     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1044     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1045     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1046   }
1047
1048   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1049     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1050     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1051     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1052     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1053     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1055
1056     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1059
1060     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1070     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1071     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1072
1073     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1074     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1075     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1076     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1077     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1078     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1079     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1080     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1081     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1083     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1084     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1085
1086     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1087     // even though v8i16 is a legal type.
1088     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1089     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1090     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1091
1092     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1093     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1094     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1095
1096     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1097     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1098
1099     for (MVT VT : MVT::fp_vector_valuetypes())
1100       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1101
1102     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1103     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1104
1105     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1106     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1107
1108     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1109     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1110
1111     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1112     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1113     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1114     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1115
1116     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1117     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1118     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1119
1120     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1121     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1122     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1123     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1124     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1125     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1126     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1127     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1128     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1129     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1130     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1131     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1132
1133     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1134     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1135     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1136     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1137
1138     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1139     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1140     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1141     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1142     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1143     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1144     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1145     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1146
1147     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1148       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1149       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1150       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1151       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1152       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1153       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1154     }
1155
1156     if (Subtarget->hasInt256()) {
1157       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1158       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1159       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1160       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1161
1162       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1163       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1164       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1165       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1166
1167       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1168       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1169       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1170       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1171
1172       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1173       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1174       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1175       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1176
1177       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1178       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1179       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1180       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1181       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1182       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1183       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1184       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1185       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1186       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1187       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1188       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1189
1190       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1191       // when we have a 256bit-wide blend with immediate.
1192       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1193
1194       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1195       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1196       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1197       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1198       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1199       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1201
1202       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1203       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1204       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1205       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1206       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1208     } else {
1209       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1210       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1211       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1212       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1213
1214       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1215       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1216       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1217       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1218
1219       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1220       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1221       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1223
1224       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1225       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1226       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1227       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1228       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1229       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1230       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1231       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1232       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1233       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1234       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1235       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1236     }
1237
1238     // In the customized shift lowering, the legal cases in AVX2 will be
1239     // recognized.
1240     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1241     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1242
1243     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1244     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1245
1246     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1247     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1248
1249     // Custom lower several nodes for 256-bit types.
1250     for (MVT VT : MVT::vector_valuetypes()) {
1251       if (VT.getScalarSizeInBits() >= 32) {
1252         setOperationAction(ISD::MLOAD,  VT, Legal);
1253         setOperationAction(ISD::MSTORE, VT, Legal);
1254       }
1255       // Extract subvector is special because the value type
1256       // (result) is 128-bit but the source is 256-bit wide.
1257       if (VT.is128BitVector()) {
1258         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1259       }
1260       // Do not attempt to custom lower other non-256-bit vectors
1261       if (!VT.is256BitVector())
1262         continue;
1263
1264       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1265       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1266       setOperationAction(ISD::VSELECT,            VT, Custom);
1267       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1268       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1269       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1270       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1271       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1272     }
1273
1274     if (Subtarget->hasInt256())
1275       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1276
1277     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1278     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1279       setOperationAction(ISD::AND,    VT, Promote);
1280       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1281       setOperationAction(ISD::OR,     VT, Promote);
1282       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1283       setOperationAction(ISD::XOR,    VT, Promote);
1284       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1285       setOperationAction(ISD::LOAD,   VT, Promote);
1286       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1287       setOperationAction(ISD::SELECT, VT, Promote);
1288       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1289     }
1290   }
1291
1292   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1293     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1294     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1295     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1296     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1297
1298     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1299     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1300     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1301
1302     for (MVT VT : MVT::fp_vector_valuetypes())
1303       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1304
1305     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1306     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1307     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1308     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1309     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1310     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1311     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1312     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1313     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1314     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1315     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1316     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1317
1318     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1319     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1320     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1321     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1322     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1323     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1324     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1325     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1326     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1327     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1329     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1332
1333     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1335     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1336     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1338     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1339
1340     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1342     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1343     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1346     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1347     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1348
1349     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1352     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1357     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1361     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1363     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1364     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1365
1366     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1367     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1368     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1369     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1370     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1371     if (Subtarget->hasVLX()){
1372       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1373       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1374       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1375       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1376       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1377
1378       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1379       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1380       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1381       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1382       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1383     }
1384     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1386     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1387     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1388     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1389     if (Subtarget->hasDQI()) {
1390       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1391       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1392
1393       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1394       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1395       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1396       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1397       if (Subtarget->hasVLX()) {
1398         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1399         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1400         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1401         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1402         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1403         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1404         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1405         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1406       }
1407     }
1408     if (Subtarget->hasVLX()) {
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1411       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1412       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1413       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1414       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1415       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1416       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1417     }
1418     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1419     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1420     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1421     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1422     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1423     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1424     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1425     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1426     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1427     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1428     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1429     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1430     if (Subtarget->hasDQI()) {
1431       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1432       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1433     }
1434     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1435     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1436     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1437     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1438     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1439     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1440     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1441     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1442     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1443     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1444
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1446     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1447     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1448     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1449     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1450
1451     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1452     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1453
1454     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1455
1456     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1457     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1458     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1459     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1460     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1461     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1462     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1463     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1464     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1465     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1466     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1467
1468     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1469     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1470     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1471     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1472     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1473     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1474     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1475     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1476
1477     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1479
1480     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1482
1483     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1484
1485     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1486     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1487
1488     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1489     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1490
1491     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1492     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1493
1494     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1496     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1497     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1498     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1499     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1500
1501     if (Subtarget->hasCDI()) {
1502       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1503       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1504       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1505       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1506
1507       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1508       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1509       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1510       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1511       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1512       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1513       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1514       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1515
1516       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1517       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1518
1519       if (Subtarget->hasVLX()) {
1520         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1521         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1522         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1523         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1524         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1525         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1526         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1527         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1528
1529         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1530         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1531         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1532         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1533       } else {
1534         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1535         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1536         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1537         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1538         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1539         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1540         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1541         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1542       }
1543     } // Subtarget->hasCDI()
1544
1545     if (Subtarget->hasDQI()) {
1546       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1547       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1548       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1549     }
1550     // Custom lower several nodes.
1551     for (MVT VT : MVT::vector_valuetypes()) {
1552       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1553       if (EltSize == 1) {
1554         setOperationAction(ISD::AND, VT, Legal);
1555         setOperationAction(ISD::OR,  VT, Legal);
1556         setOperationAction(ISD::XOR,  VT, Legal);
1557       }
1558       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1559         setOperationAction(ISD::MGATHER,  VT, Custom);
1560         setOperationAction(ISD::MSCATTER, VT, Custom);
1561       }
1562       // Extract subvector is special because the value type
1563       // (result) is 256/128-bit but the source is 512-bit wide.
1564       if (VT.is128BitVector() || VT.is256BitVector()) {
1565         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1566       }
1567       if (VT.getVectorElementType() == MVT::i1)
1568         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1569
1570       // Do not attempt to custom lower other non-512-bit vectors
1571       if (!VT.is512BitVector())
1572         continue;
1573
1574       if (EltSize >= 32) {
1575         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1576         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1577         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1578         setOperationAction(ISD::VSELECT,             VT, Legal);
1579         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1580         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1581         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1582         setOperationAction(ISD::MLOAD,               VT, Legal);
1583         setOperationAction(ISD::MSTORE,              VT, Legal);
1584       }
1585     }
1586     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1587       setOperationAction(ISD::SELECT, VT, Promote);
1588       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1589     }
1590   }// has  AVX-512
1591
1592   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1593     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1594     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1595
1596     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1597     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1598
1599     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1600     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1601     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1602     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1603     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1604     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1605     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1606     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1607     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1608     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1609     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1610     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1611     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1612     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1613     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1614     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1615     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1616     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1617     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1618     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1619     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1620     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1621     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1622     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1623     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1624     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1625     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1626     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1627     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1628     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1629     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1630     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1631     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1632     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1633     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1634     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1635     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1636     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1637     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1638     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1639     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1640     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1641
1642     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1643     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1644     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1645     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1646     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1647     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1648     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1649     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1650
1651     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1652     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1653     if (Subtarget->hasVLX())
1654       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1655
1656     if (Subtarget->hasCDI()) {
1657       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1658       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1659       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1660       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1661     }
1662
1663     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1664       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1665       setOperationAction(ISD::VSELECT,             VT, Legal);
1666     }
1667   }
1668
1669   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1670     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1671     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1672
1673     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1674     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1675     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1676     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1677     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1678     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1679     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1680     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1681     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1682     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1683     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1684     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1685
1686     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1687     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1688     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1689     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1690     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1691     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1692     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1693     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1694
1695     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1696     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1697     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1698     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1699     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1700     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1701     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1702     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1703   }
1704
1705   // We want to custom lower some of our intrinsics.
1706   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1707   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1708   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1709   if (!Subtarget->is64Bit())
1710     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1711
1712   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1713   // handle type legalization for these operations here.
1714   //
1715   // FIXME: We really should do custom legalization for addition and
1716   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1717   // than generic legalization for 64-bit multiplication-with-overflow, though.
1718   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1719     if (VT == MVT::i64 && !Subtarget->is64Bit())
1720       continue;
1721     // Add/Sub/Mul with overflow operations are custom lowered.
1722     setOperationAction(ISD::SADDO, VT, Custom);
1723     setOperationAction(ISD::UADDO, VT, Custom);
1724     setOperationAction(ISD::SSUBO, VT, Custom);
1725     setOperationAction(ISD::USUBO, VT, Custom);
1726     setOperationAction(ISD::SMULO, VT, Custom);
1727     setOperationAction(ISD::UMULO, VT, Custom);
1728   }
1729
1730   if (!Subtarget->is64Bit()) {
1731     // These libcalls are not available in 32-bit.
1732     setLibcallName(RTLIB::SHL_I128, nullptr);
1733     setLibcallName(RTLIB::SRL_I128, nullptr);
1734     setLibcallName(RTLIB::SRA_I128, nullptr);
1735   }
1736
1737   // Combine sin / cos into one node or libcall if possible.
1738   if (Subtarget->hasSinCos()) {
1739     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1740     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1741     if (Subtarget->isTargetDarwin()) {
1742       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1743       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1744       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1745       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1746     }
1747   }
1748
1749   if (Subtarget->isTargetWin64()) {
1750     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1751     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1752     setOperationAction(ISD::SREM, MVT::i128, Custom);
1753     setOperationAction(ISD::UREM, MVT::i128, Custom);
1754     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1755     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1756   }
1757
1758   // We have target-specific dag combine patterns for the following nodes:
1759   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1760   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1761   setTargetDAGCombine(ISD::BITCAST);
1762   setTargetDAGCombine(ISD::VSELECT);
1763   setTargetDAGCombine(ISD::SELECT);
1764   setTargetDAGCombine(ISD::SHL);
1765   setTargetDAGCombine(ISD::SRA);
1766   setTargetDAGCombine(ISD::SRL);
1767   setTargetDAGCombine(ISD::OR);
1768   setTargetDAGCombine(ISD::AND);
1769   setTargetDAGCombine(ISD::ADD);
1770   setTargetDAGCombine(ISD::FADD);
1771   setTargetDAGCombine(ISD::FSUB);
1772   setTargetDAGCombine(ISD::FMA);
1773   setTargetDAGCombine(ISD::SUB);
1774   setTargetDAGCombine(ISD::LOAD);
1775   setTargetDAGCombine(ISD::MLOAD);
1776   setTargetDAGCombine(ISD::STORE);
1777   setTargetDAGCombine(ISD::MSTORE);
1778   setTargetDAGCombine(ISD::ZERO_EXTEND);
1779   setTargetDAGCombine(ISD::ANY_EXTEND);
1780   setTargetDAGCombine(ISD::SIGN_EXTEND);
1781   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1782   setTargetDAGCombine(ISD::SINT_TO_FP);
1783   setTargetDAGCombine(ISD::UINT_TO_FP);
1784   setTargetDAGCombine(ISD::SETCC);
1785   setTargetDAGCombine(ISD::BUILD_VECTOR);
1786   setTargetDAGCombine(ISD::MUL);
1787   setTargetDAGCombine(ISD::XOR);
1788
1789   computeRegisterProperties(Subtarget->getRegisterInfo());
1790
1791   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1792   MaxStoresPerMemsetOptSize = 8;
1793   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1794   MaxStoresPerMemcpyOptSize = 4;
1795   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1796   MaxStoresPerMemmoveOptSize = 4;
1797   setPrefLoopAlignment(4); // 2^4 bytes.
1798
1799   // A predictable cmov does not hurt on an in-order CPU.
1800   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1801   PredictableSelectIsExpensive = !Subtarget->isAtom();
1802   EnableExtLdPromotion = true;
1803   setPrefFunctionAlignment(4); // 2^4 bytes.
1804
1805   verifyIntrinsicTables();
1806 }
1807
1808 // This has so far only been implemented for 64-bit MachO.
1809 bool X86TargetLowering::useLoadStackGuardNode() const {
1810   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1811 }
1812
1813 TargetLoweringBase::LegalizeTypeAction
1814 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1815   if (ExperimentalVectorWideningLegalization &&
1816       VT.getVectorNumElements() != 1 &&
1817       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1818     return TypeWidenVector;
1819
1820   return TargetLoweringBase::getPreferredVectorAction(VT);
1821 }
1822
1823 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1824                                           EVT VT) const {
1825   if (!VT.isVector())
1826     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1827
1828   if (VT.isSimple()) {
1829     MVT VVT = VT.getSimpleVT();
1830     const unsigned NumElts = VVT.getVectorNumElements();
1831     const MVT EltVT = VVT.getVectorElementType();
1832     if (VVT.is512BitVector()) {
1833       if (Subtarget->hasAVX512())
1834         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1835             EltVT == MVT::f32 || EltVT == MVT::f64)
1836           switch(NumElts) {
1837           case  8: return MVT::v8i1;
1838           case 16: return MVT::v16i1;
1839         }
1840       if (Subtarget->hasBWI())
1841         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1842           switch(NumElts) {
1843           case 32: return MVT::v32i1;
1844           case 64: return MVT::v64i1;
1845         }
1846     }
1847
1848     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1849       if (Subtarget->hasVLX())
1850         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1851             EltVT == MVT::f32 || EltVT == MVT::f64)
1852           switch(NumElts) {
1853           case 2: return MVT::v2i1;
1854           case 4: return MVT::v4i1;
1855           case 8: return MVT::v8i1;
1856         }
1857       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1858         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1859           switch(NumElts) {
1860           case  8: return MVT::v8i1;
1861           case 16: return MVT::v16i1;
1862           case 32: return MVT::v32i1;
1863         }
1864     }
1865   }
1866
1867   return VT.changeVectorElementTypeToInteger();
1868 }
1869
1870 /// Helper for getByValTypeAlignment to determine
1871 /// the desired ByVal argument alignment.
1872 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1873   if (MaxAlign == 16)
1874     return;
1875   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1876     if (VTy->getBitWidth() == 128)
1877       MaxAlign = 16;
1878   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1879     unsigned EltAlign = 0;
1880     getMaxByValAlign(ATy->getElementType(), EltAlign);
1881     if (EltAlign > MaxAlign)
1882       MaxAlign = EltAlign;
1883   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1884     for (auto *EltTy : STy->elements()) {
1885       unsigned EltAlign = 0;
1886       getMaxByValAlign(EltTy, EltAlign);
1887       if (EltAlign > MaxAlign)
1888         MaxAlign = EltAlign;
1889       if (MaxAlign == 16)
1890         break;
1891     }
1892   }
1893 }
1894
1895 /// Return the desired alignment for ByVal aggregate
1896 /// function arguments in the caller parameter area. For X86, aggregates
1897 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1898 /// are at 4-byte boundaries.
1899 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1900                                                   const DataLayout &DL) const {
1901   if (Subtarget->is64Bit()) {
1902     // Max of 8 and alignment of type.
1903     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1904     if (TyAlign > 8)
1905       return TyAlign;
1906     return 8;
1907   }
1908
1909   unsigned Align = 4;
1910   if (Subtarget->hasSSE1())
1911     getMaxByValAlign(Ty, Align);
1912   return Align;
1913 }
1914
1915 /// Returns the target specific optimal type for load
1916 /// and store operations as a result of memset, memcpy, and memmove
1917 /// lowering. If DstAlign is zero that means it's safe to destination
1918 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1919 /// means there isn't a need to check it against alignment requirement,
1920 /// probably because the source does not need to be loaded. If 'IsMemset' is
1921 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1922 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1923 /// source is constant so it does not need to be loaded.
1924 /// It returns EVT::Other if the type should be determined using generic
1925 /// target-independent logic.
1926 EVT
1927 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1928                                        unsigned DstAlign, unsigned SrcAlign,
1929                                        bool IsMemset, bool ZeroMemset,
1930                                        bool MemcpyStrSrc,
1931                                        MachineFunction &MF) const {
1932   const Function *F = MF.getFunction();
1933   if ((!IsMemset || ZeroMemset) &&
1934       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1935     if (Size >= 16 &&
1936         (!Subtarget->isUnalignedMem16Slow() ||
1937          ((DstAlign == 0 || DstAlign >= 16) &&
1938           (SrcAlign == 0 || SrcAlign >= 16)))) {
1939       if (Size >= 32) {
1940         // FIXME: Check if unaligned 32-byte accesses are slow.
1941         if (Subtarget->hasInt256())
1942           return MVT::v8i32;
1943         if (Subtarget->hasFp256())
1944           return MVT::v8f32;
1945       }
1946       if (Subtarget->hasSSE2())
1947         return MVT::v4i32;
1948       if (Subtarget->hasSSE1())
1949         return MVT::v4f32;
1950     } else if (!MemcpyStrSrc && Size >= 8 &&
1951                !Subtarget->is64Bit() &&
1952                Subtarget->hasSSE2()) {
1953       // Do not use f64 to lower memcpy if source is string constant. It's
1954       // better to use i32 to avoid the loads.
1955       return MVT::f64;
1956     }
1957   }
1958   // This is a compromise. If we reach here, unaligned accesses may be slow on
1959   // this target. However, creating smaller, aligned accesses could be even
1960   // slower and would certainly be a lot more code.
1961   if (Subtarget->is64Bit() && Size >= 8)
1962     return MVT::i64;
1963   return MVT::i32;
1964 }
1965
1966 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1967   if (VT == MVT::f32)
1968     return X86ScalarSSEf32;
1969   else if (VT == MVT::f64)
1970     return X86ScalarSSEf64;
1971   return true;
1972 }
1973
1974 bool
1975 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1976                                                   unsigned,
1977                                                   unsigned,
1978                                                   bool *Fast) const {
1979   if (Fast) {
1980     switch (VT.getSizeInBits()) {
1981     default:
1982       // 8-byte and under are always assumed to be fast.
1983       *Fast = true;
1984       break;
1985     case 128:
1986       *Fast = !Subtarget->isUnalignedMem16Slow();
1987       break;
1988     case 256:
1989       *Fast = !Subtarget->isUnalignedMem32Slow();
1990       break;
1991     // TODO: What about AVX-512 (512-bit) accesses?
1992     }
1993   }
1994   // Misaligned accesses of any size are always allowed.
1995   return true;
1996 }
1997
1998 /// Return the entry encoding for a jump table in the
1999 /// current function.  The returned value is a member of the
2000 /// MachineJumpTableInfo::JTEntryKind enum.
2001 unsigned X86TargetLowering::getJumpTableEncoding() const {
2002   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2003   // symbol.
2004   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2005       Subtarget->isPICStyleGOT())
2006     return MachineJumpTableInfo::EK_Custom32;
2007
2008   // Otherwise, use the normal jump table encoding heuristics.
2009   return TargetLowering::getJumpTableEncoding();
2010 }
2011
2012 bool X86TargetLowering::useSoftFloat() const {
2013   return Subtarget->useSoftFloat();
2014 }
2015
2016 const MCExpr *
2017 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2018                                              const MachineBasicBlock *MBB,
2019                                              unsigned uid,MCContext &Ctx) const{
2020   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2021          Subtarget->isPICStyleGOT());
2022   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2023   // entries.
2024   return MCSymbolRefExpr::create(MBB->getSymbol(),
2025                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2026 }
2027
2028 /// Returns relocation base for the given PIC jumptable.
2029 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2030                                                     SelectionDAG &DAG) const {
2031   if (!Subtarget->is64Bit())
2032     // This doesn't have SDLoc associated with it, but is not really the
2033     // same as a Register.
2034     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2035                        getPointerTy(DAG.getDataLayout()));
2036   return Table;
2037 }
2038
2039 /// This returns the relocation base for the given PIC jumptable,
2040 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2041 const MCExpr *X86TargetLowering::
2042 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2043                              MCContext &Ctx) const {
2044   // X86-64 uses RIP relative addressing based on the jump table label.
2045   if (Subtarget->isPICStyleRIPRel())
2046     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2047
2048   // Otherwise, the reference is relative to the PIC base.
2049   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2050 }
2051
2052 std::pair<const TargetRegisterClass *, uint8_t>
2053 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2054                                            MVT VT) const {
2055   const TargetRegisterClass *RRC = nullptr;
2056   uint8_t Cost = 1;
2057   switch (VT.SimpleTy) {
2058   default:
2059     return TargetLowering::findRepresentativeClass(TRI, VT);
2060   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2061     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2062     break;
2063   case MVT::x86mmx:
2064     RRC = &X86::VR64RegClass;
2065     break;
2066   case MVT::f32: case MVT::f64:
2067   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2068   case MVT::v4f32: case MVT::v2f64:
2069   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2070   case MVT::v4f64:
2071     RRC = &X86::VR128RegClass;
2072     break;
2073   }
2074   return std::make_pair(RRC, Cost);
2075 }
2076
2077 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2078                                                unsigned &Offset) const {
2079   if (!Subtarget->isTargetLinux())
2080     return false;
2081
2082   if (Subtarget->is64Bit()) {
2083     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2084     Offset = 0x28;
2085     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2086       AddressSpace = 256;
2087     else
2088       AddressSpace = 257;
2089   } else {
2090     // %gs:0x14 on i386
2091     Offset = 0x14;
2092     AddressSpace = 256;
2093   }
2094   return true;
2095 }
2096
2097 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2098   if (!Subtarget->isTargetAndroid())
2099     return TargetLowering::getSafeStackPointerLocation(IRB);
2100
2101   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2102   // definition of TLS_SLOT_SAFESTACK in
2103   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2104   unsigned AddressSpace, Offset;
2105   if (Subtarget->is64Bit()) {
2106     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2107     Offset = 0x48;
2108     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2109       AddressSpace = 256;
2110     else
2111       AddressSpace = 257;
2112   } else {
2113     // %gs:0x24 on i386
2114     Offset = 0x24;
2115     AddressSpace = 256;
2116   }
2117
2118   return ConstantExpr::getIntToPtr(
2119       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2120       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2121 }
2122
2123 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2124                                             unsigned DestAS) const {
2125   assert(SrcAS != DestAS && "Expected different address spaces!");
2126
2127   return SrcAS < 256 && DestAS < 256;
2128 }
2129
2130 //===----------------------------------------------------------------------===//
2131 //               Return Value Calling Convention Implementation
2132 //===----------------------------------------------------------------------===//
2133
2134 #include "X86GenCallingConv.inc"
2135
2136 bool X86TargetLowering::CanLowerReturn(
2137     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2138     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2139   SmallVector<CCValAssign, 16> RVLocs;
2140   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2141   return CCInfo.CheckReturn(Outs, RetCC_X86);
2142 }
2143
2144 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2145   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2146   return ScratchRegs;
2147 }
2148
2149 SDValue
2150 X86TargetLowering::LowerReturn(SDValue Chain,
2151                                CallingConv::ID CallConv, bool isVarArg,
2152                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2153                                const SmallVectorImpl<SDValue> &OutVals,
2154                                SDLoc dl, SelectionDAG &DAG) const {
2155   MachineFunction &MF = DAG.getMachineFunction();
2156   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2157
2158   SmallVector<CCValAssign, 16> RVLocs;
2159   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2160   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2161
2162   SDValue Flag;
2163   SmallVector<SDValue, 6> RetOps;
2164   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2165   // Operand #1 = Bytes To Pop
2166   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2167                    MVT::i16));
2168
2169   // Copy the result values into the output registers.
2170   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2171     CCValAssign &VA = RVLocs[i];
2172     assert(VA.isRegLoc() && "Can only return in registers!");
2173     SDValue ValToCopy = OutVals[i];
2174     EVT ValVT = ValToCopy.getValueType();
2175
2176     // Promote values to the appropriate types.
2177     if (VA.getLocInfo() == CCValAssign::SExt)
2178       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2179     else if (VA.getLocInfo() == CCValAssign::ZExt)
2180       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2181     else if (VA.getLocInfo() == CCValAssign::AExt) {
2182       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2183         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2184       else
2185         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2186     }
2187     else if (VA.getLocInfo() == CCValAssign::BCvt)
2188       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2189
2190     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2191            "Unexpected FP-extend for return value.");
2192
2193     // If this is x86-64, and we disabled SSE, we can't return FP values,
2194     // or SSE or MMX vectors.
2195     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2196          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2197           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2198       report_fatal_error("SSE register return with SSE disabled");
2199     }
2200     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2201     // llvm-gcc has never done it right and no one has noticed, so this
2202     // should be OK for now.
2203     if (ValVT == MVT::f64 &&
2204         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2205       report_fatal_error("SSE2 register return with SSE2 disabled");
2206
2207     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2208     // the RET instruction and handled by the FP Stackifier.
2209     if (VA.getLocReg() == X86::FP0 ||
2210         VA.getLocReg() == X86::FP1) {
2211       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2212       // change the value to the FP stack register class.
2213       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2214         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2215       RetOps.push_back(ValToCopy);
2216       // Don't emit a copytoreg.
2217       continue;
2218     }
2219
2220     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2221     // which is returned in RAX / RDX.
2222     if (Subtarget->is64Bit()) {
2223       if (ValVT == MVT::x86mmx) {
2224         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2225           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2226           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2227                                   ValToCopy);
2228           // If we don't have SSE2 available, convert to v4f32 so the generated
2229           // register is legal.
2230           if (!Subtarget->hasSSE2())
2231             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2232         }
2233       }
2234     }
2235
2236     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2237     Flag = Chain.getValue(1);
2238     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2239   }
2240
2241   // All x86 ABIs require that for returning structs by value we copy
2242   // the sret argument into %rax/%eax (depending on ABI) for the return.
2243   // We saved the argument into a virtual register in the entry block,
2244   // so now we copy the value out and into %rax/%eax.
2245   //
2246   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2247   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2248   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2249   // either case FuncInfo->setSRetReturnReg() will have been called.
2250   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2251     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2252                                      getPointerTy(MF.getDataLayout()));
2253
2254     unsigned RetValReg
2255         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2256           X86::RAX : X86::EAX;
2257     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2258     Flag = Chain.getValue(1);
2259
2260     // RAX/EAX now acts like a return value.
2261     RetOps.push_back(
2262         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2263   }
2264
2265   RetOps[0] = Chain;  // Update chain.
2266
2267   // Add the flag if we have it.
2268   if (Flag.getNode())
2269     RetOps.push_back(Flag);
2270
2271   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2272 }
2273
2274 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2275   if (N->getNumValues() != 1)
2276     return false;
2277   if (!N->hasNUsesOfValue(1, 0))
2278     return false;
2279
2280   SDValue TCChain = Chain;
2281   SDNode *Copy = *N->use_begin();
2282   if (Copy->getOpcode() == ISD::CopyToReg) {
2283     // If the copy has a glue operand, we conservatively assume it isn't safe to
2284     // perform a tail call.
2285     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2286       return false;
2287     TCChain = Copy->getOperand(0);
2288   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2289     return false;
2290
2291   bool HasRet = false;
2292   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2293        UI != UE; ++UI) {
2294     if (UI->getOpcode() != X86ISD::RET_FLAG)
2295       return false;
2296     // If we are returning more than one value, we can definitely
2297     // not make a tail call see PR19530
2298     if (UI->getNumOperands() > 4)
2299       return false;
2300     if (UI->getNumOperands() == 4 &&
2301         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2302       return false;
2303     HasRet = true;
2304   }
2305
2306   if (!HasRet)
2307     return false;
2308
2309   Chain = TCChain;
2310   return true;
2311 }
2312
2313 EVT
2314 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2315                                             ISD::NodeType ExtendKind) const {
2316   MVT ReturnMVT;
2317   // TODO: Is this also valid on 32-bit?
2318   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2319     ReturnMVT = MVT::i8;
2320   else
2321     ReturnMVT = MVT::i32;
2322
2323   EVT MinVT = getRegisterType(Context, ReturnMVT);
2324   return VT.bitsLT(MinVT) ? MinVT : VT;
2325 }
2326
2327 /// Lower the result values of a call into the
2328 /// appropriate copies out of appropriate physical registers.
2329 ///
2330 SDValue
2331 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2332                                    CallingConv::ID CallConv, bool isVarArg,
2333                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2334                                    SDLoc dl, SelectionDAG &DAG,
2335                                    SmallVectorImpl<SDValue> &InVals) const {
2336
2337   // Assign locations to each value returned by this call.
2338   SmallVector<CCValAssign, 16> RVLocs;
2339   bool Is64Bit = Subtarget->is64Bit();
2340   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2341                  *DAG.getContext());
2342   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2343
2344   // Copy all of the result registers out of their specified physreg.
2345   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2346     CCValAssign &VA = RVLocs[i];
2347     EVT CopyVT = VA.getLocVT();
2348
2349     // If this is x86-64, and we disabled SSE, we can't return FP values
2350     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2351         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2352       report_fatal_error("SSE register return with SSE disabled");
2353     }
2354
2355     // If we prefer to use the value in xmm registers, copy it out as f80 and
2356     // use a truncate to move it from fp stack reg to xmm reg.
2357     bool RoundAfterCopy = false;
2358     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2359         isScalarFPTypeInSSEReg(VA.getValVT())) {
2360       CopyVT = MVT::f80;
2361       RoundAfterCopy = (CopyVT != VA.getLocVT());
2362     }
2363
2364     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2365                                CopyVT, InFlag).getValue(1);
2366     SDValue Val = Chain.getValue(0);
2367
2368     if (RoundAfterCopy)
2369       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2370                         // This truncation won't change the value.
2371                         DAG.getIntPtrConstant(1, dl));
2372
2373     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2374       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2375
2376     InFlag = Chain.getValue(2);
2377     InVals.push_back(Val);
2378   }
2379
2380   return Chain;
2381 }
2382
2383 //===----------------------------------------------------------------------===//
2384 //                C & StdCall & Fast Calling Convention implementation
2385 //===----------------------------------------------------------------------===//
2386 //  StdCall calling convention seems to be standard for many Windows' API
2387 //  routines and around. It differs from C calling convention just a little:
2388 //  callee should clean up the stack, not caller. Symbols should be also
2389 //  decorated in some fancy way :) It doesn't support any vector arguments.
2390 //  For info on fast calling convention see Fast Calling Convention (tail call)
2391 //  implementation LowerX86_32FastCCCallTo.
2392
2393 /// CallIsStructReturn - Determines whether a call uses struct return
2394 /// semantics.
2395 enum StructReturnType {
2396   NotStructReturn,
2397   RegStructReturn,
2398   StackStructReturn
2399 };
2400 static StructReturnType
2401 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2402   if (Outs.empty())
2403     return NotStructReturn;
2404
2405   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2406   if (!Flags.isSRet())
2407     return NotStructReturn;
2408   if (Flags.isInReg())
2409     return RegStructReturn;
2410   return StackStructReturn;
2411 }
2412
2413 /// Determines whether a function uses struct return semantics.
2414 static StructReturnType
2415 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2416   if (Ins.empty())
2417     return NotStructReturn;
2418
2419   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2420   if (!Flags.isSRet())
2421     return NotStructReturn;
2422   if (Flags.isInReg())
2423     return RegStructReturn;
2424   return StackStructReturn;
2425 }
2426
2427 /// Make a copy of an aggregate at address specified by "Src" to address
2428 /// "Dst" with size and alignment information specified by the specific
2429 /// parameter attribute. The copy will be passed as a byval function parameter.
2430 static SDValue
2431 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2432                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2433                           SDLoc dl) {
2434   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2435
2436   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2437                        /*isVolatile*/false, /*AlwaysInline=*/true,
2438                        /*isTailCall*/false,
2439                        MachinePointerInfo(), MachinePointerInfo());
2440 }
2441
2442 /// Return true if the calling convention is one that we can guarantee TCO for.
2443 static bool canGuaranteeTCO(CallingConv::ID CC) {
2444   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2445           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2446 }
2447
2448 /// Return true if we might ever do TCO for calls with this calling convention.
2449 static bool mayTailCallThisCC(CallingConv::ID CC) {
2450   switch (CC) {
2451   // C calling conventions:
2452   case CallingConv::C:
2453   case CallingConv::X86_64_Win64:
2454   case CallingConv::X86_64_SysV:
2455   // Callee pop conventions:
2456   case CallingConv::X86_ThisCall:
2457   case CallingConv::X86_StdCall:
2458   case CallingConv::X86_VectorCall:
2459   case CallingConv::X86_FastCall:
2460     return true;
2461   default:
2462     return canGuaranteeTCO(CC);
2463   }
2464 }
2465
2466 /// Return true if the function is being made into a tailcall target by
2467 /// changing its ABI.
2468 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2469   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2470 }
2471
2472 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2473   auto Attr =
2474       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2475   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2476     return false;
2477
2478   CallSite CS(CI);
2479   CallingConv::ID CalleeCC = CS.getCallingConv();
2480   if (!mayTailCallThisCC(CalleeCC))
2481     return false;
2482
2483   return true;
2484 }
2485
2486 SDValue
2487 X86TargetLowering::LowerMemArgument(SDValue Chain,
2488                                     CallingConv::ID CallConv,
2489                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2490                                     SDLoc dl, SelectionDAG &DAG,
2491                                     const CCValAssign &VA,
2492                                     MachineFrameInfo *MFI,
2493                                     unsigned i) const {
2494   // Create the nodes corresponding to a load from this parameter slot.
2495   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2496   bool AlwaysUseMutable = shouldGuaranteeTCO(
2497       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2498   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2499   EVT ValVT;
2500
2501   // If value is passed by pointer we have address passed instead of the value
2502   // itself.
2503   bool ExtendedInMem = VA.isExtInLoc() &&
2504     VA.getValVT().getScalarType() == MVT::i1;
2505
2506   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2507     ValVT = VA.getLocVT();
2508   else
2509     ValVT = VA.getValVT();
2510
2511   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2512   // changed with more analysis.
2513   // In case of tail call optimization mark all arguments mutable. Since they
2514   // could be overwritten by lowering of arguments in case of a tail call.
2515   if (Flags.isByVal()) {
2516     unsigned Bytes = Flags.getByValSize();
2517     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2518     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2519     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2520   } else {
2521     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2522                                     VA.getLocMemOffset(), isImmutable);
2523     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2524     SDValue Val = DAG.getLoad(
2525         ValVT, dl, Chain, FIN,
2526         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2527         false, false, 0);
2528     return ExtendedInMem ?
2529       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2530   }
2531 }
2532
2533 // FIXME: Get this from tablegen.
2534 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2535                                                 const X86Subtarget *Subtarget) {
2536   assert(Subtarget->is64Bit());
2537
2538   if (Subtarget->isCallingConvWin64(CallConv)) {
2539     static const MCPhysReg GPR64ArgRegsWin64[] = {
2540       X86::RCX, X86::RDX, X86::R8,  X86::R9
2541     };
2542     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2543   }
2544
2545   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2546     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2547   };
2548   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2549 }
2550
2551 // FIXME: Get this from tablegen.
2552 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2553                                                 CallingConv::ID CallConv,
2554                                                 const X86Subtarget *Subtarget) {
2555   assert(Subtarget->is64Bit());
2556   if (Subtarget->isCallingConvWin64(CallConv)) {
2557     // The XMM registers which might contain var arg parameters are shadowed
2558     // in their paired GPR.  So we only need to save the GPR to their home
2559     // slots.
2560     // TODO: __vectorcall will change this.
2561     return None;
2562   }
2563
2564   const Function *Fn = MF.getFunction();
2565   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2566   bool isSoftFloat = Subtarget->useSoftFloat();
2567   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2568          "SSE register cannot be used when SSE is disabled!");
2569   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2570     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2571     // registers.
2572     return None;
2573
2574   static const MCPhysReg XMMArgRegs64Bit[] = {
2575     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2576     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2577   };
2578   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2579 }
2580
2581 SDValue X86TargetLowering::LowerFormalArguments(
2582     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2583     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2584     SmallVectorImpl<SDValue> &InVals) const {
2585   MachineFunction &MF = DAG.getMachineFunction();
2586   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2587   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2588
2589   const Function* Fn = MF.getFunction();
2590   if (Fn->hasExternalLinkage() &&
2591       Subtarget->isTargetCygMing() &&
2592       Fn->getName() == "main")
2593     FuncInfo->setForceFramePointer(true);
2594
2595   MachineFrameInfo *MFI = MF.getFrameInfo();
2596   bool Is64Bit = Subtarget->is64Bit();
2597   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2598
2599   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2600          "Var args not supported with calling convention fastcc, ghc or hipe");
2601
2602   // Assign locations to all of the incoming arguments.
2603   SmallVector<CCValAssign, 16> ArgLocs;
2604   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2605
2606   // Allocate shadow area for Win64
2607   if (IsWin64)
2608     CCInfo.AllocateStack(32, 8);
2609
2610   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2611
2612   unsigned LastVal = ~0U;
2613   SDValue ArgValue;
2614   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2615     CCValAssign &VA = ArgLocs[i];
2616     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2617     // places.
2618     assert(VA.getValNo() != LastVal &&
2619            "Don't support value assigned to multiple locs yet");
2620     (void)LastVal;
2621     LastVal = VA.getValNo();
2622
2623     if (VA.isRegLoc()) {
2624       EVT RegVT = VA.getLocVT();
2625       const TargetRegisterClass *RC;
2626       if (RegVT == MVT::i32)
2627         RC = &X86::GR32RegClass;
2628       else if (Is64Bit && RegVT == MVT::i64)
2629         RC = &X86::GR64RegClass;
2630       else if (RegVT == MVT::f32)
2631         RC = &X86::FR32RegClass;
2632       else if (RegVT == MVT::f64)
2633         RC = &X86::FR64RegClass;
2634       else if (RegVT.is512BitVector())
2635         RC = &X86::VR512RegClass;
2636       else if (RegVT.is256BitVector())
2637         RC = &X86::VR256RegClass;
2638       else if (RegVT.is128BitVector())
2639         RC = &X86::VR128RegClass;
2640       else if (RegVT == MVT::x86mmx)
2641         RC = &X86::VR64RegClass;
2642       else if (RegVT == MVT::i1)
2643         RC = &X86::VK1RegClass;
2644       else if (RegVT == MVT::v8i1)
2645         RC = &X86::VK8RegClass;
2646       else if (RegVT == MVT::v16i1)
2647         RC = &X86::VK16RegClass;
2648       else if (RegVT == MVT::v32i1)
2649         RC = &X86::VK32RegClass;
2650       else if (RegVT == MVT::v64i1)
2651         RC = &X86::VK64RegClass;
2652       else
2653         llvm_unreachable("Unknown argument type!");
2654
2655       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2656       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2657
2658       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2659       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2660       // right size.
2661       if (VA.getLocInfo() == CCValAssign::SExt)
2662         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2663                                DAG.getValueType(VA.getValVT()));
2664       else if (VA.getLocInfo() == CCValAssign::ZExt)
2665         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2666                                DAG.getValueType(VA.getValVT()));
2667       else if (VA.getLocInfo() == CCValAssign::BCvt)
2668         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2669
2670       if (VA.isExtInLoc()) {
2671         // Handle MMX values passed in XMM regs.
2672         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2673           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2674         else
2675           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2676       }
2677     } else {
2678       assert(VA.isMemLoc());
2679       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2680     }
2681
2682     // If value is passed via pointer - do a load.
2683     if (VA.getLocInfo() == CCValAssign::Indirect)
2684       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2685                              MachinePointerInfo(), false, false, false, 0);
2686
2687     InVals.push_back(ArgValue);
2688   }
2689
2690   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2691     // All x86 ABIs require that for returning structs by value we copy the
2692     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2693     // the argument into a virtual register so that we can access it from the
2694     // return points.
2695     if (Ins[i].Flags.isSRet()) {
2696       unsigned Reg = FuncInfo->getSRetReturnReg();
2697       if (!Reg) {
2698         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2699         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2700         FuncInfo->setSRetReturnReg(Reg);
2701       }
2702       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2703       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2704       break;
2705     }
2706   }
2707
2708   unsigned StackSize = CCInfo.getNextStackOffset();
2709   // Align stack specially for tail calls.
2710   if (shouldGuaranteeTCO(CallConv,
2711                          MF.getTarget().Options.GuaranteedTailCallOpt))
2712     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2713
2714   // If the function takes variable number of arguments, make a frame index for
2715   // the start of the first vararg value... for expansion of llvm.va_start. We
2716   // can skip this if there are no va_start calls.
2717   if (MFI->hasVAStart() &&
2718       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2719                    CallConv != CallingConv::X86_ThisCall))) {
2720     FuncInfo->setVarArgsFrameIndex(
2721         MFI->CreateFixedObject(1, StackSize, true));
2722   }
2723
2724   // Figure out if XMM registers are in use.
2725   assert(!(Subtarget->useSoftFloat() &&
2726            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2727          "SSE register cannot be used when SSE is disabled!");
2728
2729   // 64-bit calling conventions support varargs and register parameters, so we
2730   // have to do extra work to spill them in the prologue.
2731   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2732     // Find the first unallocated argument registers.
2733     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2734     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2735     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2736     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2737     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2738            "SSE register cannot be used when SSE is disabled!");
2739
2740     // Gather all the live in physical registers.
2741     SmallVector<SDValue, 6> LiveGPRs;
2742     SmallVector<SDValue, 8> LiveXMMRegs;
2743     SDValue ALVal;
2744     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2745       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2746       LiveGPRs.push_back(
2747           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2748     }
2749     if (!ArgXMMs.empty()) {
2750       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2751       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2752       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2753         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2754         LiveXMMRegs.push_back(
2755             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2756       }
2757     }
2758
2759     if (IsWin64) {
2760       // Get to the caller-allocated home save location.  Add 8 to account
2761       // for the return address.
2762       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2763       FuncInfo->setRegSaveFrameIndex(
2764           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2765       // Fixup to set vararg frame on shadow area (4 x i64).
2766       if (NumIntRegs < 4)
2767         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2768     } else {
2769       // For X86-64, if there are vararg parameters that are passed via
2770       // registers, then we must store them to their spots on the stack so
2771       // they may be loaded by deferencing the result of va_next.
2772       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2773       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2774       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2775           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2776     }
2777
2778     // Store the integer parameter registers.
2779     SmallVector<SDValue, 8> MemOps;
2780     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2781                                       getPointerTy(DAG.getDataLayout()));
2782     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2783     for (SDValue Val : LiveGPRs) {
2784       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2785                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2786       SDValue Store =
2787           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2788                        MachinePointerInfo::getFixedStack(
2789                            DAG.getMachineFunction(),
2790                            FuncInfo->getRegSaveFrameIndex(), Offset),
2791                        false, false, 0);
2792       MemOps.push_back(Store);
2793       Offset += 8;
2794     }
2795
2796     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2797       // Now store the XMM (fp + vector) parameter registers.
2798       SmallVector<SDValue, 12> SaveXMMOps;
2799       SaveXMMOps.push_back(Chain);
2800       SaveXMMOps.push_back(ALVal);
2801       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2802                              FuncInfo->getRegSaveFrameIndex(), dl));
2803       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2804                              FuncInfo->getVarArgsFPOffset(), dl));
2805       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2806                         LiveXMMRegs.end());
2807       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2808                                    MVT::Other, SaveXMMOps));
2809     }
2810
2811     if (!MemOps.empty())
2812       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2813   }
2814
2815   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2816     // Find the largest legal vector type.
2817     MVT VecVT = MVT::Other;
2818     // FIXME: Only some x86_32 calling conventions support AVX512.
2819     if (Subtarget->hasAVX512() &&
2820         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2821                      CallConv == CallingConv::Intel_OCL_BI)))
2822       VecVT = MVT::v16f32;
2823     else if (Subtarget->hasAVX())
2824       VecVT = MVT::v8f32;
2825     else if (Subtarget->hasSSE2())
2826       VecVT = MVT::v4f32;
2827
2828     // We forward some GPRs and some vector types.
2829     SmallVector<MVT, 2> RegParmTypes;
2830     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2831     RegParmTypes.push_back(IntVT);
2832     if (VecVT != MVT::Other)
2833       RegParmTypes.push_back(VecVT);
2834
2835     // Compute the set of forwarded registers. The rest are scratch.
2836     SmallVectorImpl<ForwardedRegister> &Forwards =
2837         FuncInfo->getForwardedMustTailRegParms();
2838     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2839
2840     // Conservatively forward AL on x86_64, since it might be used for varargs.
2841     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2842       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2843       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2844     }
2845
2846     // Copy all forwards from physical to virtual registers.
2847     for (ForwardedRegister &F : Forwards) {
2848       // FIXME: Can we use a less constrained schedule?
2849       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2850       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2851       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2852     }
2853   }
2854
2855   // Some CCs need callee pop.
2856   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2857                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2858     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2859   } else {
2860     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2861     // If this is an sret function, the return should pop the hidden pointer.
2862     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2863         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2864         argsAreStructReturn(Ins) == StackStructReturn)
2865       FuncInfo->setBytesToPopOnReturn(4);
2866   }
2867
2868   if (!Is64Bit) {
2869     // RegSaveFrameIndex is X86-64 only.
2870     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2871     if (CallConv == CallingConv::X86_FastCall ||
2872         CallConv == CallingConv::X86_ThisCall)
2873       // fastcc functions can't have varargs.
2874       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2875   }
2876
2877   FuncInfo->setArgumentStackSize(StackSize);
2878
2879   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2880     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2881     if (Personality == EHPersonality::CoreCLR) {
2882       assert(Is64Bit);
2883       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2884       // that we'd prefer this slot be allocated towards the bottom of the frame
2885       // (i.e. near the stack pointer after allocating the frame).  Every
2886       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2887       // offset from the bottom of this and each funclet's frame must be the
2888       // same, so the size of funclets' (mostly empty) frames is dictated by
2889       // how far this slot is from the bottom (since they allocate just enough
2890       // space to accomodate holding this slot at the correct offset).
2891       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2892       EHInfo->PSPSymFrameIdx = PSPSymFI;
2893     }
2894   }
2895
2896   return Chain;
2897 }
2898
2899 SDValue
2900 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2901                                     SDValue StackPtr, SDValue Arg,
2902                                     SDLoc dl, SelectionDAG &DAG,
2903                                     const CCValAssign &VA,
2904                                     ISD::ArgFlagsTy Flags) const {
2905   unsigned LocMemOffset = VA.getLocMemOffset();
2906   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2907   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2908                        StackPtr, PtrOff);
2909   if (Flags.isByVal())
2910     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2911
2912   return DAG.getStore(
2913       Chain, dl, Arg, PtrOff,
2914       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2915       false, false, 0);
2916 }
2917
2918 /// Emit a load of return address if tail call
2919 /// optimization is performed and it is required.
2920 SDValue
2921 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2922                                            SDValue &OutRetAddr, SDValue Chain,
2923                                            bool IsTailCall, bool Is64Bit,
2924                                            int FPDiff, SDLoc dl) const {
2925   // Adjust the Return address stack slot.
2926   EVT VT = getPointerTy(DAG.getDataLayout());
2927   OutRetAddr = getReturnAddressFrameIndex(DAG);
2928
2929   // Load the "old" Return address.
2930   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2931                            false, false, false, 0);
2932   return SDValue(OutRetAddr.getNode(), 1);
2933 }
2934
2935 /// Emit a store of the return address if tail call
2936 /// optimization is performed and it is required (FPDiff!=0).
2937 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2938                                         SDValue Chain, SDValue RetAddrFrIdx,
2939                                         EVT PtrVT, unsigned SlotSize,
2940                                         int FPDiff, SDLoc dl) {
2941   // Store the return address to the appropriate stack slot.
2942   if (!FPDiff) return Chain;
2943   // Calculate the new stack slot for the return address.
2944   int NewReturnAddrFI =
2945     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2946                                          false);
2947   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2948   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2949                        MachinePointerInfo::getFixedStack(
2950                            DAG.getMachineFunction(), NewReturnAddrFI),
2951                        false, false, 0);
2952   return Chain;
2953 }
2954
2955 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2956 /// operation of specified width.
2957 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
2958                        SDValue V2) {
2959   unsigned NumElems = VT.getVectorNumElements();
2960   SmallVector<int, 8> Mask;
2961   Mask.push_back(NumElems);
2962   for (unsigned i = 1; i != NumElems; ++i)
2963     Mask.push_back(i);
2964   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2965 }
2966
2967 SDValue
2968 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2969                              SmallVectorImpl<SDValue> &InVals) const {
2970   SelectionDAG &DAG                     = CLI.DAG;
2971   SDLoc &dl                             = CLI.DL;
2972   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2973   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2974   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2975   SDValue Chain                         = CLI.Chain;
2976   SDValue Callee                        = CLI.Callee;
2977   CallingConv::ID CallConv              = CLI.CallConv;
2978   bool &isTailCall                      = CLI.IsTailCall;
2979   bool isVarArg                         = CLI.IsVarArg;
2980
2981   MachineFunction &MF = DAG.getMachineFunction();
2982   bool Is64Bit        = Subtarget->is64Bit();
2983   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2984   StructReturnType SR = callIsStructReturn(Outs);
2985   bool IsSibcall      = false;
2986   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2987   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2988
2989   if (Attr.getValueAsString() == "true")
2990     isTailCall = false;
2991
2992   if (Subtarget->isPICStyleGOT() &&
2993       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2994     // If we are using a GOT, disable tail calls to external symbols with
2995     // default visibility. Tail calling such a symbol requires using a GOT
2996     // relocation, which forces early binding of the symbol. This breaks code
2997     // that require lazy function symbol resolution. Using musttail or
2998     // GuaranteedTailCallOpt will override this.
2999     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3000     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3001                G->getGlobal()->hasDefaultVisibility()))
3002       isTailCall = false;
3003   }
3004
3005   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3006   if (IsMustTail) {
3007     // Force this to be a tail call.  The verifier rules are enough to ensure
3008     // that we can lower this successfully without moving the return address
3009     // around.
3010     isTailCall = true;
3011   } else if (isTailCall) {
3012     // Check if it's really possible to do a tail call.
3013     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3014                     isVarArg, SR != NotStructReturn,
3015                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3016                     Outs, OutVals, Ins, DAG);
3017
3018     // Sibcalls are automatically detected tailcalls which do not require
3019     // ABI changes.
3020     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3021       IsSibcall = true;
3022
3023     if (isTailCall)
3024       ++NumTailCalls;
3025   }
3026
3027   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3028          "Var args not supported with calling convention fastcc, ghc or hipe");
3029
3030   // Analyze operands of the call, assigning locations to each operand.
3031   SmallVector<CCValAssign, 16> ArgLocs;
3032   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3033
3034   // Allocate shadow area for Win64
3035   if (IsWin64)
3036     CCInfo.AllocateStack(32, 8);
3037
3038   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3039
3040   // Get a count of how many bytes are to be pushed on the stack.
3041   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3042   if (IsSibcall)
3043     // This is a sibcall. The memory operands are available in caller's
3044     // own caller's stack.
3045     NumBytes = 0;
3046   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3047            canGuaranteeTCO(CallConv))
3048     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3049
3050   int FPDiff = 0;
3051   if (isTailCall && !IsSibcall && !IsMustTail) {
3052     // Lower arguments at fp - stackoffset + fpdiff.
3053     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3054
3055     FPDiff = NumBytesCallerPushed - NumBytes;
3056
3057     // Set the delta of movement of the returnaddr stackslot.
3058     // But only set if delta is greater than previous delta.
3059     if (FPDiff < X86Info->getTCReturnAddrDelta())
3060       X86Info->setTCReturnAddrDelta(FPDiff);
3061   }
3062
3063   unsigned NumBytesToPush = NumBytes;
3064   unsigned NumBytesToPop = NumBytes;
3065
3066   // If we have an inalloca argument, all stack space has already been allocated
3067   // for us and be right at the top of the stack.  We don't support multiple
3068   // arguments passed in memory when using inalloca.
3069   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3070     NumBytesToPush = 0;
3071     if (!ArgLocs.back().isMemLoc())
3072       report_fatal_error("cannot use inalloca attribute on a register "
3073                          "parameter");
3074     if (ArgLocs.back().getLocMemOffset() != 0)
3075       report_fatal_error("any parameter with the inalloca attribute must be "
3076                          "the only memory argument");
3077   }
3078
3079   if (!IsSibcall)
3080     Chain = DAG.getCALLSEQ_START(
3081         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3082
3083   SDValue RetAddrFrIdx;
3084   // Load return address for tail calls.
3085   if (isTailCall && FPDiff)
3086     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3087                                     Is64Bit, FPDiff, dl);
3088
3089   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3090   SmallVector<SDValue, 8> MemOpChains;
3091   SDValue StackPtr;
3092
3093   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3094   // of tail call optimization arguments are handle later.
3095   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3096   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3097     // Skip inalloca arguments, they have already been written.
3098     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3099     if (Flags.isInAlloca())
3100       continue;
3101
3102     CCValAssign &VA = ArgLocs[i];
3103     EVT RegVT = VA.getLocVT();
3104     SDValue Arg = OutVals[i];
3105     bool isByVal = Flags.isByVal();
3106
3107     // Promote the value if needed.
3108     switch (VA.getLocInfo()) {
3109     default: llvm_unreachable("Unknown loc info!");
3110     case CCValAssign::Full: break;
3111     case CCValAssign::SExt:
3112       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3113       break;
3114     case CCValAssign::ZExt:
3115       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3116       break;
3117     case CCValAssign::AExt:
3118       if (Arg.getValueType().isVector() &&
3119           Arg.getValueType().getVectorElementType() == MVT::i1)
3120         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3121       else if (RegVT.is128BitVector()) {
3122         // Special case: passing MMX values in XMM registers.
3123         Arg = DAG.getBitcast(MVT::i64, Arg);
3124         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3125         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3126       } else
3127         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3128       break;
3129     case CCValAssign::BCvt:
3130       Arg = DAG.getBitcast(RegVT, Arg);
3131       break;
3132     case CCValAssign::Indirect: {
3133       // Store the argument.
3134       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3135       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3136       Chain = DAG.getStore(
3137           Chain, dl, Arg, SpillSlot,
3138           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3139           false, false, 0);
3140       Arg = SpillSlot;
3141       break;
3142     }
3143     }
3144
3145     if (VA.isRegLoc()) {
3146       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3147       if (isVarArg && IsWin64) {
3148         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3149         // shadow reg if callee is a varargs function.
3150         unsigned ShadowReg = 0;
3151         switch (VA.getLocReg()) {
3152         case X86::XMM0: ShadowReg = X86::RCX; break;
3153         case X86::XMM1: ShadowReg = X86::RDX; break;
3154         case X86::XMM2: ShadowReg = X86::R8; break;
3155         case X86::XMM3: ShadowReg = X86::R9; break;
3156         }
3157         if (ShadowReg)
3158           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3159       }
3160     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3161       assert(VA.isMemLoc());
3162       if (!StackPtr.getNode())
3163         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3164                                       getPointerTy(DAG.getDataLayout()));
3165       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3166                                              dl, DAG, VA, Flags));
3167     }
3168   }
3169
3170   if (!MemOpChains.empty())
3171     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3172
3173   if (Subtarget->isPICStyleGOT()) {
3174     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3175     // GOT pointer.
3176     if (!isTailCall) {
3177       RegsToPass.push_back(std::make_pair(
3178           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3179                                           getPointerTy(DAG.getDataLayout()))));
3180     } else {
3181       // If we are tail calling and generating PIC/GOT style code load the
3182       // address of the callee into ECX. The value in ecx is used as target of
3183       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3184       // for tail calls on PIC/GOT architectures. Normally we would just put the
3185       // address of GOT into ebx and then call target@PLT. But for tail calls
3186       // ebx would be restored (since ebx is callee saved) before jumping to the
3187       // target@PLT.
3188
3189       // Note: The actual moving to ECX is done further down.
3190       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3191       if (G && !G->getGlobal()->hasLocalLinkage() &&
3192           G->getGlobal()->hasDefaultVisibility())
3193         Callee = LowerGlobalAddress(Callee, DAG);
3194       else if (isa<ExternalSymbolSDNode>(Callee))
3195         Callee = LowerExternalSymbol(Callee, DAG);
3196     }
3197   }
3198
3199   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3200     // From AMD64 ABI document:
3201     // For calls that may call functions that use varargs or stdargs
3202     // (prototype-less calls or calls to functions containing ellipsis (...) in
3203     // the declaration) %al is used as hidden argument to specify the number
3204     // of SSE registers used. The contents of %al do not need to match exactly
3205     // the number of registers, but must be an ubound on the number of SSE
3206     // registers used and is in the range 0 - 8 inclusive.
3207
3208     // Count the number of XMM registers allocated.
3209     static const MCPhysReg XMMArgRegs[] = {
3210       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3211       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3212     };
3213     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3214     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3215            && "SSE registers cannot be used when SSE is disabled");
3216
3217     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3218                                         DAG.getConstant(NumXMMRegs, dl,
3219                                                         MVT::i8)));
3220   }
3221
3222   if (isVarArg && IsMustTail) {
3223     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3224     for (const auto &F : Forwards) {
3225       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3226       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3227     }
3228   }
3229
3230   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3231   // don't need this because the eligibility check rejects calls that require
3232   // shuffling arguments passed in memory.
3233   if (!IsSibcall && isTailCall) {
3234     // Force all the incoming stack arguments to be loaded from the stack
3235     // before any new outgoing arguments are stored to the stack, because the
3236     // outgoing stack slots may alias the incoming argument stack slots, and
3237     // the alias isn't otherwise explicit. This is slightly more conservative
3238     // than necessary, because it means that each store effectively depends
3239     // on every argument instead of just those arguments it would clobber.
3240     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3241
3242     SmallVector<SDValue, 8> MemOpChains2;
3243     SDValue FIN;
3244     int FI = 0;
3245     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3246       CCValAssign &VA = ArgLocs[i];
3247       if (VA.isRegLoc())
3248         continue;
3249       assert(VA.isMemLoc());
3250       SDValue Arg = OutVals[i];
3251       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3252       // Skip inalloca arguments.  They don't require any work.
3253       if (Flags.isInAlloca())
3254         continue;
3255       // Create frame index.
3256       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3257       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3258       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3259       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3260
3261       if (Flags.isByVal()) {
3262         // Copy relative to framepointer.
3263         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3264         if (!StackPtr.getNode())
3265           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3266                                         getPointerTy(DAG.getDataLayout()));
3267         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3268                              StackPtr, Source);
3269
3270         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3271                                                          ArgChain,
3272                                                          Flags, DAG, dl));
3273       } else {
3274         // Store relative to framepointer.
3275         MemOpChains2.push_back(DAG.getStore(
3276             ArgChain, dl, Arg, FIN,
3277             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3278             false, false, 0));
3279       }
3280     }
3281
3282     if (!MemOpChains2.empty())
3283       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3284
3285     // Store the return address to the appropriate stack slot.
3286     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3287                                      getPointerTy(DAG.getDataLayout()),
3288                                      RegInfo->getSlotSize(), FPDiff, dl);
3289   }
3290
3291   // Build a sequence of copy-to-reg nodes chained together with token chain
3292   // and flag operands which copy the outgoing args into registers.
3293   SDValue InFlag;
3294   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3295     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3296                              RegsToPass[i].second, InFlag);
3297     InFlag = Chain.getValue(1);
3298   }
3299
3300   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3301     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3302     // In the 64-bit large code model, we have to make all calls
3303     // through a register, since the call instruction's 32-bit
3304     // pc-relative offset may not be large enough to hold the whole
3305     // address.
3306   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3307     // If the callee is a GlobalAddress node (quite common, every direct call
3308     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3309     // it.
3310     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3311
3312     // We should use extra load for direct calls to dllimported functions in
3313     // non-JIT mode.
3314     const GlobalValue *GV = G->getGlobal();
3315     if (!GV->hasDLLImportStorageClass()) {
3316       unsigned char OpFlags = 0;
3317       bool ExtraLoad = false;
3318       unsigned WrapperKind = ISD::DELETED_NODE;
3319
3320       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3321       // external symbols most go through the PLT in PIC mode.  If the symbol
3322       // has hidden or protected visibility, or if it is static or local, then
3323       // we don't need to use the PLT - we can directly call it.
3324       if (Subtarget->isTargetELF() &&
3325           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3326           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3327         OpFlags = X86II::MO_PLT;
3328       } else if (Subtarget->isPICStyleStubAny() &&
3329                  !GV->isStrongDefinitionForLinker() &&
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       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3337                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3338         // If the function is marked as non-lazy, generate an indirect call
3339         // which loads from the GOT directly. This avoids runtime overhead
3340         // at the cost of eager binding (and one extra byte of encoding).
3341         OpFlags = X86II::MO_GOTPCREL;
3342         WrapperKind = X86ISD::WrapperRIP;
3343         ExtraLoad = true;
3344       }
3345
3346       Callee = DAG.getTargetGlobalAddress(
3347           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3348
3349       // Add a wrapper if needed.
3350       if (WrapperKind != ISD::DELETED_NODE)
3351         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3352                              getPointerTy(DAG.getDataLayout()), Callee);
3353       // Add extra indirection if needed.
3354       if (ExtraLoad)
3355         Callee = DAG.getLoad(
3356             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3357             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3358             false, 0);
3359     }
3360   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3361     unsigned char OpFlags = 0;
3362
3363     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3364     // external symbols should go through the PLT.
3365     if (Subtarget->isTargetELF() &&
3366         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3367       OpFlags = X86II::MO_PLT;
3368     } else if (Subtarget->isPICStyleStubAny() &&
3369                (!Subtarget->getTargetTriple().isMacOSX() ||
3370                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3371       // PC-relative references to external symbols should go through $stub,
3372       // unless we're building with the leopard linker or later, which
3373       // automatically synthesizes these stubs.
3374       OpFlags = X86II::MO_DARWIN_STUB;
3375     }
3376
3377     Callee = DAG.getTargetExternalSymbol(
3378         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3379   } else if (Subtarget->isTarget64BitILP32() &&
3380              Callee->getValueType(0) == MVT::i32) {
3381     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3382     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3383   }
3384
3385   // Returns a chain & a flag for retval copy to use.
3386   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3387   SmallVector<SDValue, 8> Ops;
3388
3389   if (!IsSibcall && isTailCall) {
3390     Chain = DAG.getCALLSEQ_END(Chain,
3391                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3392                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3393     InFlag = Chain.getValue(1);
3394   }
3395
3396   Ops.push_back(Chain);
3397   Ops.push_back(Callee);
3398
3399   if (isTailCall)
3400     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3401
3402   // Add argument registers to the end of the list so that they are known live
3403   // into the call.
3404   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3405     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3406                                   RegsToPass[i].second.getValueType()));
3407
3408   // Add a register mask operand representing the call-preserved registers.
3409   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3410   assert(Mask && "Missing call preserved mask for calling convention");
3411
3412   // If this is an invoke in a 32-bit function using a funclet-based
3413   // personality, assume the function clobbers all registers. If an exception
3414   // is thrown, the runtime will not restore CSRs.
3415   // FIXME: Model this more precisely so that we can register allocate across
3416   // the normal edge and spill and fill across the exceptional edge.
3417   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3418     const Function *CallerFn = MF.getFunction();
3419     EHPersonality Pers =
3420         CallerFn->hasPersonalityFn()
3421             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3422             : EHPersonality::Unknown;
3423     if (isFuncletEHPersonality(Pers))
3424       Mask = RegInfo->getNoPreservedMask();
3425   }
3426
3427   Ops.push_back(DAG.getRegisterMask(Mask));
3428
3429   if (InFlag.getNode())
3430     Ops.push_back(InFlag);
3431
3432   if (isTailCall) {
3433     // We used to do:
3434     //// If this is the first return lowered for this function, add the regs
3435     //// to the liveout set for the function.
3436     // This isn't right, although it's probably harmless on x86; liveouts
3437     // should be computed from returns not tail calls.  Consider a void
3438     // function making a tail call to a function returning int.
3439     MF.getFrameInfo()->setHasTailCall();
3440     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3441   }
3442
3443   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3444   InFlag = Chain.getValue(1);
3445
3446   // Create the CALLSEQ_END node.
3447   unsigned NumBytesForCalleeToPop;
3448   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3449                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3450     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3451   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3452            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3453            SR == StackStructReturn)
3454     // If this is a call to a struct-return function, the callee
3455     // pops the hidden struct pointer, so we have to push it back.
3456     // This is common for Darwin/X86, Linux & Mingw32 targets.
3457     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3458     NumBytesForCalleeToPop = 4;
3459   else
3460     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3461
3462   // Returns a flag for retval copy to use.
3463   if (!IsSibcall) {
3464     Chain = DAG.getCALLSEQ_END(Chain,
3465                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3466                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3467                                                      true),
3468                                InFlag, dl);
3469     InFlag = Chain.getValue(1);
3470   }
3471
3472   // Handle result values, copying them out of physregs into vregs that we
3473   // return.
3474   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3475                          Ins, dl, DAG, InVals);
3476 }
3477
3478 //===----------------------------------------------------------------------===//
3479 //                Fast Calling Convention (tail call) implementation
3480 //===----------------------------------------------------------------------===//
3481
3482 //  Like std call, callee cleans arguments, convention except that ECX is
3483 //  reserved for storing the tail called function address. Only 2 registers are
3484 //  free for argument passing (inreg). Tail call optimization is performed
3485 //  provided:
3486 //                * tailcallopt is enabled
3487 //                * caller/callee are fastcc
3488 //  On X86_64 architecture with GOT-style position independent code only local
3489 //  (within module) calls are supported at the moment.
3490 //  To keep the stack aligned according to platform abi the function
3491 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3492 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3493 //  If a tail called function callee has more arguments than the caller the
3494 //  caller needs to make sure that there is room to move the RETADDR to. This is
3495 //  achieved by reserving an area the size of the argument delta right after the
3496 //  original RETADDR, but before the saved framepointer or the spilled registers
3497 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3498 //  stack layout:
3499 //    arg1
3500 //    arg2
3501 //    RETADDR
3502 //    [ new RETADDR
3503 //      move area ]
3504 //    (possible EBP)
3505 //    ESI
3506 //    EDI
3507 //    local1 ..
3508
3509 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3510 /// requirement.
3511 unsigned
3512 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3513                                                SelectionDAG& DAG) const {
3514   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3515   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3516   unsigned StackAlignment = TFI.getStackAlignment();
3517   uint64_t AlignMask = StackAlignment - 1;
3518   int64_t Offset = StackSize;
3519   unsigned SlotSize = RegInfo->getSlotSize();
3520   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3521     // Number smaller than 12 so just add the difference.
3522     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3523   } else {
3524     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3525     Offset = ((~AlignMask) & Offset) + StackAlignment +
3526       (StackAlignment-SlotSize);
3527   }
3528   return Offset;
3529 }
3530
3531 /// Return true if the given stack call argument is already available in the
3532 /// same position (relatively) of the caller's incoming argument stack.
3533 static
3534 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3535                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3536                          const X86InstrInfo *TII) {
3537   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3538   int FI = INT_MAX;
3539   if (Arg.getOpcode() == ISD::CopyFromReg) {
3540     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3541     if (!TargetRegisterInfo::isVirtualRegister(VR))
3542       return false;
3543     MachineInstr *Def = MRI->getVRegDef(VR);
3544     if (!Def)
3545       return false;
3546     if (!Flags.isByVal()) {
3547       if (!TII->isLoadFromStackSlot(Def, FI))
3548         return false;
3549     } else {
3550       unsigned Opcode = Def->getOpcode();
3551       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3552            Opcode == X86::LEA64_32r) &&
3553           Def->getOperand(1).isFI()) {
3554         FI = Def->getOperand(1).getIndex();
3555         Bytes = Flags.getByValSize();
3556       } else
3557         return false;
3558     }
3559   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3560     if (Flags.isByVal())
3561       // ByVal argument is passed in as a pointer but it's now being
3562       // dereferenced. e.g.
3563       // define @foo(%struct.X* %A) {
3564       //   tail call @bar(%struct.X* byval %A)
3565       // }
3566       return false;
3567     SDValue Ptr = Ld->getBasePtr();
3568     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3569     if (!FINode)
3570       return false;
3571     FI = FINode->getIndex();
3572   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3573     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3574     FI = FINode->getIndex();
3575     Bytes = Flags.getByValSize();
3576   } else
3577     return false;
3578
3579   assert(FI != INT_MAX);
3580   if (!MFI->isFixedObjectIndex(FI))
3581     return false;
3582   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3583 }
3584
3585 /// Check whether the call is eligible for tail call optimization. Targets
3586 /// that want to do tail call optimization should implement this function.
3587 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3588     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3589     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3590     const SmallVectorImpl<ISD::OutputArg> &Outs,
3591     const SmallVectorImpl<SDValue> &OutVals,
3592     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3593   if (!mayTailCallThisCC(CalleeCC))
3594     return false;
3595
3596   // If -tailcallopt is specified, make fastcc functions tail-callable.
3597   MachineFunction &MF = DAG.getMachineFunction();
3598   const Function *CallerF = MF.getFunction();
3599
3600   // If the function return type is x86_fp80 and the callee return type is not,
3601   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3602   // perform a tailcall optimization here.
3603   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3604     return false;
3605
3606   CallingConv::ID CallerCC = CallerF->getCallingConv();
3607   bool CCMatch = CallerCC == CalleeCC;
3608   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3609   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3610
3611   // Win64 functions have extra shadow space for argument homing. Don't do the
3612   // sibcall if the caller and callee have mismatched expectations for this
3613   // space.
3614   if (IsCalleeWin64 != IsCallerWin64)
3615     return false;
3616
3617   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3618     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3619       return true;
3620     return false;
3621   }
3622
3623   // Look for obvious safe cases to perform tail call optimization that do not
3624   // require ABI changes. This is what gcc calls sibcall.
3625
3626   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3627   // emit a special epilogue.
3628   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3629   if (RegInfo->needsStackRealignment(MF))
3630     return false;
3631
3632   // Also avoid sibcall optimization if either caller or callee uses struct
3633   // return semantics.
3634   if (isCalleeStructRet || isCallerStructRet)
3635     return false;
3636
3637   // Do not sibcall optimize vararg calls unless all arguments are passed via
3638   // registers.
3639   if (isVarArg && !Outs.empty()) {
3640     // Optimizing for varargs on Win64 is unlikely to be safe without
3641     // additional testing.
3642     if (IsCalleeWin64 || IsCallerWin64)
3643       return false;
3644
3645     SmallVector<CCValAssign, 16> ArgLocs;
3646     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3647                    *DAG.getContext());
3648
3649     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3650     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3651       if (!ArgLocs[i].isRegLoc())
3652         return false;
3653   }
3654
3655   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3656   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3657   // this into a sibcall.
3658   bool Unused = false;
3659   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3660     if (!Ins[i].Used) {
3661       Unused = true;
3662       break;
3663     }
3664   }
3665   if (Unused) {
3666     SmallVector<CCValAssign, 16> RVLocs;
3667     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3668                    *DAG.getContext());
3669     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3670     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3671       CCValAssign &VA = RVLocs[i];
3672       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3673         return false;
3674     }
3675   }
3676
3677   // If the calling conventions do not match, then we'd better make sure the
3678   // results are returned in the same way as what the caller expects.
3679   if (!CCMatch) {
3680     SmallVector<CCValAssign, 16> RVLocs1;
3681     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3682                     *DAG.getContext());
3683     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3684
3685     SmallVector<CCValAssign, 16> RVLocs2;
3686     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3687                     *DAG.getContext());
3688     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3689
3690     if (RVLocs1.size() != RVLocs2.size())
3691       return false;
3692     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3693       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3694         return false;
3695       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3696         return false;
3697       if (RVLocs1[i].isRegLoc()) {
3698         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3699           return false;
3700       } else {
3701         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3702           return false;
3703       }
3704     }
3705   }
3706
3707   unsigned StackArgsSize = 0;
3708
3709   // If the callee takes no arguments then go on to check the results of the
3710   // call.
3711   if (!Outs.empty()) {
3712     // Check if stack adjustment is needed. For now, do not do this if any
3713     // argument is passed on the stack.
3714     SmallVector<CCValAssign, 16> ArgLocs;
3715     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3716                    *DAG.getContext());
3717
3718     // Allocate shadow area for Win64
3719     if (IsCalleeWin64)
3720       CCInfo.AllocateStack(32, 8);
3721
3722     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3723     StackArgsSize = CCInfo.getNextStackOffset();
3724
3725     if (CCInfo.getNextStackOffset()) {
3726       // Check if the arguments are already laid out in the right way as
3727       // the caller's fixed stack objects.
3728       MachineFrameInfo *MFI = MF.getFrameInfo();
3729       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3730       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3731       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3732         CCValAssign &VA = ArgLocs[i];
3733         SDValue Arg = OutVals[i];
3734         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3735         if (VA.getLocInfo() == CCValAssign::Indirect)
3736           return false;
3737         if (!VA.isRegLoc()) {
3738           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3739                                    MFI, MRI, TII))
3740             return false;
3741         }
3742       }
3743     }
3744
3745     // If the tailcall address may be in a register, then make sure it's
3746     // possible to register allocate for it. In 32-bit, the call address can
3747     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3748     // callee-saved registers are restored. These happen to be the same
3749     // registers used to pass 'inreg' arguments so watch out for those.
3750     if (!Subtarget->is64Bit() &&
3751         ((!isa<GlobalAddressSDNode>(Callee) &&
3752           !isa<ExternalSymbolSDNode>(Callee)) ||
3753          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3754       unsigned NumInRegs = 0;
3755       // In PIC we need an extra register to formulate the address computation
3756       // for the callee.
3757       unsigned MaxInRegs =
3758         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3759
3760       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3761         CCValAssign &VA = ArgLocs[i];
3762         if (!VA.isRegLoc())
3763           continue;
3764         unsigned Reg = VA.getLocReg();
3765         switch (Reg) {
3766         default: break;
3767         case X86::EAX: case X86::EDX: case X86::ECX:
3768           if (++NumInRegs == MaxInRegs)
3769             return false;
3770           break;
3771         }
3772       }
3773     }
3774   }
3775
3776   bool CalleeWillPop =
3777       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3778                        MF.getTarget().Options.GuaranteedTailCallOpt);
3779
3780   if (unsigned BytesToPop =
3781           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3782     // If we have bytes to pop, the callee must pop them.
3783     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3784     if (!CalleePopMatches)
3785       return false;
3786   } else if (CalleeWillPop && StackArgsSize > 0) {
3787     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3788     return false;
3789   }
3790
3791   return true;
3792 }
3793
3794 FastISel *
3795 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3796                                   const TargetLibraryInfo *libInfo) const {
3797   return X86::createFastISel(funcInfo, libInfo);
3798 }
3799
3800 //===----------------------------------------------------------------------===//
3801 //                           Other Lowering Hooks
3802 //===----------------------------------------------------------------------===//
3803
3804 static bool MayFoldLoad(SDValue Op) {
3805   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3806 }
3807
3808 static bool MayFoldIntoStore(SDValue Op) {
3809   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3810 }
3811
3812 static bool isTargetShuffle(unsigned Opcode) {
3813   switch(Opcode) {
3814   default: return false;
3815   case X86ISD::BLENDI:
3816   case X86ISD::PSHUFB:
3817   case X86ISD::PSHUFD:
3818   case X86ISD::PSHUFHW:
3819   case X86ISD::PSHUFLW:
3820   case X86ISD::SHUFP:
3821   case X86ISD::PALIGNR:
3822   case X86ISD::MOVLHPS:
3823   case X86ISD::MOVLHPD:
3824   case X86ISD::MOVHLPS:
3825   case X86ISD::MOVLPS:
3826   case X86ISD::MOVLPD:
3827   case X86ISD::MOVSHDUP:
3828   case X86ISD::MOVSLDUP:
3829   case X86ISD::MOVDDUP:
3830   case X86ISD::MOVSS:
3831   case X86ISD::MOVSD:
3832   case X86ISD::UNPCKL:
3833   case X86ISD::UNPCKH:
3834   case X86ISD::VPERMILPI:
3835   case X86ISD::VPERM2X128:
3836   case X86ISD::VPERMI:
3837   case X86ISD::VPERMV:
3838   case X86ISD::VPERMV3:
3839     return true;
3840   }
3841 }
3842
3843 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3844                                     SDValue V1, unsigned TargetMask,
3845                                     SelectionDAG &DAG) {
3846   switch(Opc) {
3847   default: llvm_unreachable("Unknown x86 shuffle node");
3848   case X86ISD::PSHUFD:
3849   case X86ISD::PSHUFHW:
3850   case X86ISD::PSHUFLW:
3851   case X86ISD::VPERMILPI:
3852   case X86ISD::VPERMI:
3853     return DAG.getNode(Opc, dl, VT, V1,
3854                        DAG.getConstant(TargetMask, dl, MVT::i8));
3855   }
3856 }
3857
3858 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3859                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3860   switch(Opc) {
3861   default: llvm_unreachable("Unknown x86 shuffle node");
3862   case X86ISD::MOVLHPS:
3863   case X86ISD::MOVLHPD:
3864   case X86ISD::MOVHLPS:
3865   case X86ISD::MOVLPS:
3866   case X86ISD::MOVLPD:
3867   case X86ISD::MOVSS:
3868   case X86ISD::MOVSD:
3869   case X86ISD::UNPCKL:
3870   case X86ISD::UNPCKH:
3871     return DAG.getNode(Opc, dl, VT, V1, V2);
3872   }
3873 }
3874
3875 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3876   MachineFunction &MF = DAG.getMachineFunction();
3877   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3878   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3879   int ReturnAddrIndex = FuncInfo->getRAIndex();
3880
3881   if (ReturnAddrIndex == 0) {
3882     // Set up a frame object for the return address.
3883     unsigned SlotSize = RegInfo->getSlotSize();
3884     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3885                                                            -(int64_t)SlotSize,
3886                                                            false);
3887     FuncInfo->setRAIndex(ReturnAddrIndex);
3888   }
3889
3890   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3891 }
3892
3893 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3894                                        bool hasSymbolicDisplacement) {
3895   // Offset should fit into 32 bit immediate field.
3896   if (!isInt<32>(Offset))
3897     return false;
3898
3899   // If we don't have a symbolic displacement - we don't have any extra
3900   // restrictions.
3901   if (!hasSymbolicDisplacement)
3902     return true;
3903
3904   // FIXME: Some tweaks might be needed for medium code model.
3905   if (M != CodeModel::Small && M != CodeModel::Kernel)
3906     return false;
3907
3908   // For small code model we assume that latest object is 16MB before end of 31
3909   // bits boundary. We may also accept pretty large negative constants knowing
3910   // that all objects are in the positive half of address space.
3911   if (M == CodeModel::Small && Offset < 16*1024*1024)
3912     return true;
3913
3914   // For kernel code model we know that all object resist in the negative half
3915   // of 32bits address space. We may not accept negative offsets, since they may
3916   // be just off and we may accept pretty large positive ones.
3917   if (M == CodeModel::Kernel && Offset >= 0)
3918     return true;
3919
3920   return false;
3921 }
3922
3923 /// Determines whether the callee is required to pop its own arguments.
3924 /// Callee pop is necessary to support tail calls.
3925 bool X86::isCalleePop(CallingConv::ID CallingConv,
3926                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3927   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3928   // can guarantee TCO.
3929   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3930     return true;
3931
3932   switch (CallingConv) {
3933   default:
3934     return false;
3935   case CallingConv::X86_StdCall:
3936   case CallingConv::X86_FastCall:
3937   case CallingConv::X86_ThisCall:
3938   case CallingConv::X86_VectorCall:
3939     return !is64Bit;
3940   }
3941 }
3942
3943 /// \brief Return true if the condition is an unsigned comparison operation.
3944 static bool isX86CCUnsigned(unsigned X86CC) {
3945   switch (X86CC) {
3946   default: llvm_unreachable("Invalid integer condition!");
3947   case X86::COND_E:     return true;
3948   case X86::COND_G:     return false;
3949   case X86::COND_GE:    return false;
3950   case X86::COND_L:     return false;
3951   case X86::COND_LE:    return false;
3952   case X86::COND_NE:    return true;
3953   case X86::COND_B:     return true;
3954   case X86::COND_A:     return true;
3955   case X86::COND_BE:    return true;
3956   case X86::COND_AE:    return true;
3957   }
3958 }
3959
3960 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3961 /// condition code, returning the condition code and the LHS/RHS of the
3962 /// comparison to make.
3963 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3964                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3965   if (!isFP) {
3966     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3967       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3968         // X > -1   -> X == 0, jump !sign.
3969         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3970         return X86::COND_NS;
3971       }
3972       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3973         // X < 0   -> X == 0, jump on sign.
3974         return X86::COND_S;
3975       }
3976       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3977         // X < 1   -> X <= 0
3978         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3979         return X86::COND_LE;
3980       }
3981     }
3982
3983     switch (SetCCOpcode) {
3984     default: llvm_unreachable("Invalid integer condition!");
3985     case ISD::SETEQ:  return X86::COND_E;
3986     case ISD::SETGT:  return X86::COND_G;
3987     case ISD::SETGE:  return X86::COND_GE;
3988     case ISD::SETLT:  return X86::COND_L;
3989     case ISD::SETLE:  return X86::COND_LE;
3990     case ISD::SETNE:  return X86::COND_NE;
3991     case ISD::SETULT: return X86::COND_B;
3992     case ISD::SETUGT: return X86::COND_A;
3993     case ISD::SETULE: return X86::COND_BE;
3994     case ISD::SETUGE: return X86::COND_AE;
3995     }
3996   }
3997
3998   // First determine if it is required or is profitable to flip the operands.
3999
4000   // If LHS is a foldable load, but RHS is not, flip the condition.
4001   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4002       !ISD::isNON_EXTLoad(RHS.getNode())) {
4003     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4004     std::swap(LHS, RHS);
4005   }
4006
4007   switch (SetCCOpcode) {
4008   default: break;
4009   case ISD::SETOLT:
4010   case ISD::SETOLE:
4011   case ISD::SETUGT:
4012   case ISD::SETUGE:
4013     std::swap(LHS, RHS);
4014     break;
4015   }
4016
4017   // On a floating point condition, the flags are set as follows:
4018   // ZF  PF  CF   op
4019   //  0 | 0 | 0 | X > Y
4020   //  0 | 0 | 1 | X < Y
4021   //  1 | 0 | 0 | X == Y
4022   //  1 | 1 | 1 | unordered
4023   switch (SetCCOpcode) {
4024   default: llvm_unreachable("Condcode should be pre-legalized away");
4025   case ISD::SETUEQ:
4026   case ISD::SETEQ:   return X86::COND_E;
4027   case ISD::SETOLT:              // flipped
4028   case ISD::SETOGT:
4029   case ISD::SETGT:   return X86::COND_A;
4030   case ISD::SETOLE:              // flipped
4031   case ISD::SETOGE:
4032   case ISD::SETGE:   return X86::COND_AE;
4033   case ISD::SETUGT:              // flipped
4034   case ISD::SETULT:
4035   case ISD::SETLT:   return X86::COND_B;
4036   case ISD::SETUGE:              // flipped
4037   case ISD::SETULE:
4038   case ISD::SETLE:   return X86::COND_BE;
4039   case ISD::SETONE:
4040   case ISD::SETNE:   return X86::COND_NE;
4041   case ISD::SETUO:   return X86::COND_P;
4042   case ISD::SETO:    return X86::COND_NP;
4043   case ISD::SETOEQ:
4044   case ISD::SETUNE:  return X86::COND_INVALID;
4045   }
4046 }
4047
4048 /// Is there a floating point cmov for the specific X86 condition code?
4049 /// Current x86 isa includes the following FP cmov instructions:
4050 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4051 static bool hasFPCMov(unsigned X86CC) {
4052   switch (X86CC) {
4053   default:
4054     return false;
4055   case X86::COND_B:
4056   case X86::COND_BE:
4057   case X86::COND_E:
4058   case X86::COND_P:
4059   case X86::COND_A:
4060   case X86::COND_AE:
4061   case X86::COND_NE:
4062   case X86::COND_NP:
4063     return true;
4064   }
4065 }
4066
4067 /// Returns true if the target can instruction select the
4068 /// specified FP immediate natively. If false, the legalizer will
4069 /// materialize the FP immediate as a load from a constant pool.
4070 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4071   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4072     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4073       return true;
4074   }
4075   return false;
4076 }
4077
4078 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4079                                               ISD::LoadExtType ExtTy,
4080                                               EVT NewVT) const {
4081   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4082   // relocation target a movq or addq instruction: don't let the load shrink.
4083   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4084   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4085     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4086       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4087   return true;
4088 }
4089
4090 /// \brief Returns true if it is beneficial to convert a load of a constant
4091 /// to just the constant itself.
4092 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4093                                                           Type *Ty) const {
4094   assert(Ty->isIntegerTy());
4095
4096   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4097   if (BitSize == 0 || BitSize > 64)
4098     return false;
4099   return true;
4100 }
4101
4102 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4103                                                 unsigned Index) const {
4104   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4105     return false;
4106
4107   return (Index == 0 || Index == ResVT.getVectorNumElements());
4108 }
4109
4110 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4111   // Speculate cttz only if we can directly use TZCNT.
4112   return Subtarget->hasBMI();
4113 }
4114
4115 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4116   // Speculate ctlz only if we can directly use LZCNT.
4117   return Subtarget->hasLZCNT();
4118 }
4119
4120 /// Return true if every element in Mask, beginning
4121 /// from position Pos and ending in Pos+Size is undef.
4122 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4123   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4124     if (0 <= Mask[i])
4125       return false;
4126   return true;
4127 }
4128
4129 /// Return true if Val is undef or if its value falls within the
4130 /// specified range (L, H].
4131 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4132   return (Val < 0) || (Val >= Low && Val < Hi);
4133 }
4134
4135 /// Val is either less than zero (undef) or equal to the specified value.
4136 static bool isUndefOrEqual(int Val, int CmpVal) {
4137   return (Val < 0 || Val == CmpVal);
4138 }
4139
4140 /// Return true if every element in Mask, beginning
4141 /// from position Pos and ending in Pos+Size, falls within the specified
4142 /// sequential range (Low, Low+Size]. or is undef.
4143 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4144                                        unsigned Pos, unsigned Size, int Low) {
4145   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4146     if (!isUndefOrEqual(Mask[i], Low))
4147       return false;
4148   return true;
4149 }
4150
4151 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4152 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4153 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4154   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4155   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4156     return false;
4157
4158   // The index should be aligned on a vecWidth-bit boundary.
4159   uint64_t Index =
4160     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4161
4162   MVT VT = N->getSimpleValueType(0);
4163   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4164   bool Result = (Index * ElSize) % vecWidth == 0;
4165
4166   return Result;
4167 }
4168
4169 /// Return true if the specified INSERT_SUBVECTOR
4170 /// operand specifies a subvector insert that is suitable for input to
4171 /// insertion of 128 or 256-bit subvectors
4172 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4173   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4174   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4175     return false;
4176   // The index should be aligned on a vecWidth-bit boundary.
4177   uint64_t Index =
4178     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4179
4180   MVT VT = N->getSimpleValueType(0);
4181   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4182   bool Result = (Index * ElSize) % vecWidth == 0;
4183
4184   return Result;
4185 }
4186
4187 bool X86::isVINSERT128Index(SDNode *N) {
4188   return isVINSERTIndex(N, 128);
4189 }
4190
4191 bool X86::isVINSERT256Index(SDNode *N) {
4192   return isVINSERTIndex(N, 256);
4193 }
4194
4195 bool X86::isVEXTRACT128Index(SDNode *N) {
4196   return isVEXTRACTIndex(N, 128);
4197 }
4198
4199 bool X86::isVEXTRACT256Index(SDNode *N) {
4200   return isVEXTRACTIndex(N, 256);
4201 }
4202
4203 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4204   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4205   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4206          "Illegal extract subvector for VEXTRACT");
4207
4208   uint64_t Index =
4209     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4210
4211   MVT VecVT = N->getOperand(0).getSimpleValueType();
4212   MVT ElVT = VecVT.getVectorElementType();
4213
4214   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4215   return Index / NumElemsPerChunk;
4216 }
4217
4218 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4219   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4220   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4221          "Illegal insert subvector for VINSERT");
4222
4223   uint64_t Index =
4224     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4225
4226   MVT VecVT = N->getSimpleValueType(0);
4227   MVT ElVT = VecVT.getVectorElementType();
4228
4229   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4230   return Index / NumElemsPerChunk;
4231 }
4232
4233 /// Return the appropriate immediate to extract the specified
4234 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4235 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4236   return getExtractVEXTRACTImmediate(N, 128);
4237 }
4238
4239 /// Return the appropriate immediate to extract the specified
4240 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4241 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4242   return getExtractVEXTRACTImmediate(N, 256);
4243 }
4244
4245 /// Return the appropriate immediate to insert at the specified
4246 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4247 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4248   return getInsertVINSERTImmediate(N, 128);
4249 }
4250
4251 /// Return the appropriate immediate to insert at the specified
4252 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4253 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4254   return getInsertVINSERTImmediate(N, 256);
4255 }
4256
4257 /// Returns true if V is a constant integer zero.
4258 static bool isZero(SDValue V) {
4259   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4260   return C && C->isNullValue();
4261 }
4262
4263 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4264 bool X86::isZeroNode(SDValue Elt) {
4265   if (isZero(Elt))
4266     return true;
4267   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4268     return CFP->getValueAPF().isPosZero();
4269   return false;
4270 }
4271
4272 // Build a vector of constants
4273 // Use an UNDEF node if MaskElt == -1.
4274 // Spilt 64-bit constants in the 32-bit mode.
4275 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4276                               SelectionDAG &DAG,
4277                               SDLoc dl, bool IsMask = false) {
4278
4279   SmallVector<SDValue, 32>  Ops;
4280   bool Split = false;
4281
4282   MVT ConstVecVT = VT;
4283   unsigned NumElts = VT.getVectorNumElements();
4284   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4285   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4286     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4287     Split = true;
4288   }
4289
4290   MVT EltVT = ConstVecVT.getVectorElementType();
4291   for (unsigned i = 0; i < NumElts; ++i) {
4292     bool IsUndef = Values[i] < 0 && IsMask;
4293     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4294       DAG.getConstant(Values[i], dl, EltVT);
4295     Ops.push_back(OpNode);
4296     if (Split)
4297       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4298                     DAG.getConstant(0, dl, EltVT));
4299   }
4300   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4301   if (Split)
4302     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4303   return ConstsNode;
4304 }
4305
4306 /// Returns a vector of specified type with all zero elements.
4307 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4308                              SelectionDAG &DAG, SDLoc dl) {
4309   assert(VT.isVector() && "Expected a vector type");
4310
4311   // Always build SSE zero vectors as <4 x i32> bitcasted
4312   // to their dest type. This ensures they get CSE'd.
4313   SDValue Vec;
4314   if (VT.is128BitVector()) {  // SSE
4315     if (Subtarget->hasSSE2()) {  // SSE2
4316       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4317       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4318     } else { // SSE1
4319       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4320       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4321     }
4322   } else if (VT.is256BitVector()) { // AVX
4323     if (Subtarget->hasInt256()) { // AVX2
4324       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4325       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4326       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4327     } else {
4328       // 256-bit logic and arithmetic instructions in AVX are all
4329       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4330       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4331       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4332       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4333     }
4334   } else if (VT.is512BitVector()) { // AVX-512
4335       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4336       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4337                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4338       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4339   } else if (VT.getVectorElementType() == MVT::i1) {
4340
4341     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4342             && "Unexpected vector type");
4343     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4344             && "Unexpected vector type");
4345     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4346     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4347     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4348   } else
4349     llvm_unreachable("Unexpected vector type");
4350
4351   return DAG.getBitcast(VT, Vec);
4352 }
4353
4354 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4355                                 SelectionDAG &DAG, SDLoc dl,
4356                                 unsigned vectorWidth) {
4357   assert((vectorWidth == 128 || vectorWidth == 256) &&
4358          "Unsupported vector width");
4359   EVT VT = Vec.getValueType();
4360   EVT ElVT = VT.getVectorElementType();
4361   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4362   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4363                                   VT.getVectorNumElements()/Factor);
4364
4365   // Extract from UNDEF is UNDEF.
4366   if (Vec.getOpcode() == ISD::UNDEF)
4367     return DAG.getUNDEF(ResultVT);
4368
4369   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4370   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4371   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4372
4373   // This is the index of the first element of the vectorWidth-bit chunk
4374   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4375   IdxVal &= ~(ElemsPerChunk - 1);
4376
4377   // If the input is a buildvector just emit a smaller one.
4378   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4379     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4380                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4381
4382   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4383   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4384 }
4385
4386 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4387 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4388 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4389 /// instructions or a simple subregister reference. Idx is an index in the
4390 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4391 /// lowering EXTRACT_VECTOR_ELT operations easier.
4392 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4393                                    SelectionDAG &DAG, SDLoc dl) {
4394   assert((Vec.getValueType().is256BitVector() ||
4395           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4396   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4397 }
4398
4399 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4400 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4401                                    SelectionDAG &DAG, SDLoc dl) {
4402   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4403   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4404 }
4405
4406 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4407                                unsigned IdxVal, SelectionDAG &DAG,
4408                                SDLoc dl, unsigned vectorWidth) {
4409   assert((vectorWidth == 128 || vectorWidth == 256) &&
4410          "Unsupported vector width");
4411   // Inserting UNDEF is Result
4412   if (Vec.getOpcode() == ISD::UNDEF)
4413     return Result;
4414   EVT VT = Vec.getValueType();
4415   EVT ElVT = VT.getVectorElementType();
4416   EVT ResultVT = Result.getValueType();
4417
4418   // Insert the relevant vectorWidth bits.
4419   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4420   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4421
4422   // This is the index of the first element of the vectorWidth-bit chunk
4423   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4424   IdxVal &= ~(ElemsPerChunk - 1);
4425
4426   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4427   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4428 }
4429
4430 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4431 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4432 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4433 /// simple superregister reference.  Idx is an index in the 128 bits
4434 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4435 /// lowering INSERT_VECTOR_ELT operations easier.
4436 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4437                                   SelectionDAG &DAG, SDLoc dl) {
4438   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4439
4440   // For insertion into the zero index (low half) of a 256-bit vector, it is
4441   // more efficient to generate a blend with immediate instead of an insert*128.
4442   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4443   // extend the subvector to the size of the result vector. Make sure that
4444   // we are not recursing on that node by checking for undef here.
4445   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4446       Result.getOpcode() != ISD::UNDEF) {
4447     EVT ResultVT = Result.getValueType();
4448     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4449     SDValue Undef = DAG.getUNDEF(ResultVT);
4450     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4451                                  Vec, ZeroIndex);
4452
4453     // The blend instruction, and therefore its mask, depend on the data type.
4454     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4455     if (ScalarType.isFloatingPoint()) {
4456       // Choose either vblendps (float) or vblendpd (double).
4457       unsigned ScalarSize = ScalarType.getSizeInBits();
4458       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4459       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4460       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4461       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4462     }
4463
4464     const X86Subtarget &Subtarget =
4465     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4466
4467     // AVX2 is needed for 256-bit integer blend support.
4468     // Integers must be cast to 32-bit because there is only vpblendd;
4469     // vpblendw can't be used for this because it has a handicapped mask.
4470
4471     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4472     // is still more efficient than using the wrong domain vinsertf128 that
4473     // will be created by InsertSubVector().
4474     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4475
4476     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4477     Vec256 = DAG.getBitcast(CastVT, Vec256);
4478     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4479     return DAG.getBitcast(ResultVT, Vec256);
4480   }
4481
4482   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4483 }
4484
4485 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4486                                   SelectionDAG &DAG, SDLoc dl) {
4487   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4488   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4489 }
4490
4491 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4492 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4493 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4494 /// large BUILD_VECTORS.
4495 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4496                                    unsigned NumElems, SelectionDAG &DAG,
4497                                    SDLoc dl) {
4498   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4499   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4500 }
4501
4502 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4503                                    unsigned NumElems, SelectionDAG &DAG,
4504                                    SDLoc dl) {
4505   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4506   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4507 }
4508
4509 /// Returns a vector of specified type with all bits set.
4510 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4511 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4512 /// Then bitcast to their original type, ensuring they get CSE'd.
4513 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4514                              SelectionDAG &DAG, SDLoc dl) {
4515   assert(VT.isVector() && "Expected a vector type");
4516
4517   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4518   SDValue Vec;
4519   if (VT.is512BitVector()) {
4520     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4521                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4522     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4523   } else if (VT.is256BitVector()) {
4524     if (Subtarget->hasInt256()) { // AVX2
4525       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4526       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4527     } else { // AVX
4528       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4529       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4530     }
4531   } else if (VT.is128BitVector()) {
4532     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4533   } else
4534     llvm_unreachable("Unexpected vector type");
4535
4536   return DAG.getBitcast(VT, Vec);
4537 }
4538
4539 /// Returns a vector_shuffle node for an unpackl operation.
4540 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4541                           SDValue V2) {
4542   unsigned NumElems = VT.getVectorNumElements();
4543   SmallVector<int, 8> Mask;
4544   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4545     Mask.push_back(i);
4546     Mask.push_back(i + NumElems);
4547   }
4548   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4549 }
4550
4551 /// Returns a vector_shuffle node for an unpackh operation.
4552 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4553                           SDValue V2) {
4554   unsigned NumElems = VT.getVectorNumElements();
4555   SmallVector<int, 8> Mask;
4556   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4557     Mask.push_back(i + Half);
4558     Mask.push_back(i + NumElems + Half);
4559   }
4560   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4561 }
4562
4563 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4564 /// This produces a shuffle where the low element of V2 is swizzled into the
4565 /// zero/undef vector, landing at element Idx.
4566 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4567 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4568                                            bool IsZero,
4569                                            const X86Subtarget *Subtarget,
4570                                            SelectionDAG &DAG) {
4571   MVT VT = V2.getSimpleValueType();
4572   SDValue V1 = IsZero
4573     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4574   unsigned NumElems = VT.getVectorNumElements();
4575   SmallVector<int, 16> MaskVec;
4576   for (unsigned i = 0; i != NumElems; ++i)
4577     // If this is the insertion idx, put the low elt of V2 here.
4578     MaskVec.push_back(i == Idx ? NumElems : i);
4579   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4580 }
4581
4582 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4583 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4584 /// uses one source. Note that this will set IsUnary for shuffles which use a
4585 /// single input multiple times, and in those cases it will
4586 /// adjust the mask to only have indices within that single input.
4587 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4588 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4589                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4590   unsigned NumElems = VT.getVectorNumElements();
4591   SDValue ImmN;
4592
4593   IsUnary = false;
4594   bool IsFakeUnary = false;
4595   switch(N->getOpcode()) {
4596   case X86ISD::BLENDI:
4597     ImmN = N->getOperand(N->getNumOperands()-1);
4598     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4599     break;
4600   case X86ISD::SHUFP:
4601     ImmN = N->getOperand(N->getNumOperands()-1);
4602     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4603     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4604     break;
4605   case X86ISD::UNPCKH:
4606     DecodeUNPCKHMask(VT, Mask);
4607     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4608     break;
4609   case X86ISD::UNPCKL:
4610     DecodeUNPCKLMask(VT, Mask);
4611     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4612     break;
4613   case X86ISD::MOVHLPS:
4614     DecodeMOVHLPSMask(NumElems, Mask);
4615     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4616     break;
4617   case X86ISD::MOVLHPS:
4618     DecodeMOVLHPSMask(NumElems, Mask);
4619     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4620     break;
4621   case X86ISD::PALIGNR:
4622     ImmN = N->getOperand(N->getNumOperands()-1);
4623     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4624     break;
4625   case X86ISD::PSHUFD:
4626   case X86ISD::VPERMILPI:
4627     ImmN = N->getOperand(N->getNumOperands()-1);
4628     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4629     IsUnary = true;
4630     break;
4631   case X86ISD::PSHUFHW:
4632     ImmN = N->getOperand(N->getNumOperands()-1);
4633     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4634     IsUnary = true;
4635     break;
4636   case X86ISD::PSHUFLW:
4637     ImmN = N->getOperand(N->getNumOperands()-1);
4638     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4639     IsUnary = true;
4640     break;
4641   case X86ISD::PSHUFB: {
4642     IsUnary = true;
4643     SDValue MaskNode = N->getOperand(1);
4644     while (MaskNode->getOpcode() == ISD::BITCAST)
4645       MaskNode = MaskNode->getOperand(0);
4646
4647     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4648       // If we have a build-vector, then things are easy.
4649       MVT VT = MaskNode.getSimpleValueType();
4650       assert(VT.isVector() &&
4651              "Can't produce a non-vector with a build_vector!");
4652       if (!VT.isInteger())
4653         return false;
4654
4655       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4656
4657       SmallVector<uint64_t, 32> RawMask;
4658       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4659         SDValue Op = MaskNode->getOperand(i);
4660         if (Op->getOpcode() == ISD::UNDEF) {
4661           RawMask.push_back((uint64_t)SM_SentinelUndef);
4662           continue;
4663         }
4664         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4665         if (!CN)
4666           return false;
4667         APInt MaskElement = CN->getAPIntValue();
4668
4669         // We now have to decode the element which could be any integer size and
4670         // extract each byte of it.
4671         for (int j = 0; j < NumBytesPerElement; ++j) {
4672           // Note that this is x86 and so always little endian: the low byte is
4673           // the first byte of the mask.
4674           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4675           MaskElement = MaskElement.lshr(8);
4676         }
4677       }
4678       DecodePSHUFBMask(RawMask, Mask);
4679       break;
4680     }
4681
4682     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4683     if (!MaskLoad)
4684       return false;
4685
4686     SDValue Ptr = MaskLoad->getBasePtr();
4687     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4688         Ptr->getOpcode() == X86ISD::WrapperRIP)
4689       Ptr = Ptr->getOperand(0);
4690
4691     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4692     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4693       return false;
4694
4695     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4696       DecodePSHUFBMask(C, Mask);
4697       if (Mask.empty())
4698         return false;
4699       break;
4700     }
4701
4702     return false;
4703   }
4704   case X86ISD::VPERMI:
4705     ImmN = N->getOperand(N->getNumOperands()-1);
4706     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4707     IsUnary = true;
4708     break;
4709   case X86ISD::MOVSS:
4710   case X86ISD::MOVSD:
4711     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4712     break;
4713   case X86ISD::VPERM2X128:
4714     ImmN = N->getOperand(N->getNumOperands()-1);
4715     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4716     if (Mask.empty()) return false;
4717     // Mask only contains negative index if an element is zero.
4718     if (std::any_of(Mask.begin(), Mask.end(),
4719                     [](int M){ return M == SM_SentinelZero; }))
4720       return false;
4721     break;
4722   case X86ISD::MOVSLDUP:
4723     DecodeMOVSLDUPMask(VT, Mask);
4724     IsUnary = true;
4725     break;
4726   case X86ISD::MOVSHDUP:
4727     DecodeMOVSHDUPMask(VT, Mask);
4728     IsUnary = true;
4729     break;
4730   case X86ISD::MOVDDUP:
4731     DecodeMOVDDUPMask(VT, Mask);
4732     IsUnary = true;
4733     break;
4734   case X86ISD::MOVLHPD:
4735   case X86ISD::MOVLPD:
4736   case X86ISD::MOVLPS:
4737     // Not yet implemented
4738     return false;
4739   case X86ISD::VPERMV: {
4740     IsUnary = true;
4741     SDValue MaskNode = N->getOperand(0);
4742     while (MaskNode->getOpcode() == ISD::BITCAST)
4743       MaskNode = MaskNode->getOperand(0);
4744
4745     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4746     SmallVector<uint64_t, 32> RawMask;
4747     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4748       // If we have a build-vector, then things are easy.
4749       assert(MaskNode.getSimpleValueType().isInteger() &&
4750              MaskNode.getSimpleValueType().getVectorNumElements() ==
4751              VT.getVectorNumElements());
4752
4753       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4754         SDValue Op = MaskNode->getOperand(i);
4755         if (Op->getOpcode() == ISD::UNDEF)
4756           RawMask.push_back((uint64_t)SM_SentinelUndef);
4757         else if (isa<ConstantSDNode>(Op)) {
4758           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4759           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4760         } else
4761           return false;
4762       }
4763       DecodeVPERMVMask(RawMask, Mask);
4764       break;
4765     }
4766     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4767       unsigned NumEltsInMask = MaskNode->getNumOperands();
4768       MaskNode = MaskNode->getOperand(0);
4769       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4770       if (CN) {
4771         APInt MaskEltValue = CN->getAPIntValue();
4772         for (unsigned i = 0; i < NumEltsInMask; ++i)
4773           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4774         DecodeVPERMVMask(RawMask, Mask);
4775         break;
4776       }
4777       // It may be a scalar load
4778     }
4779
4780     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4781     if (!MaskLoad)
4782       return false;
4783
4784     SDValue Ptr = MaskLoad->getBasePtr();
4785     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4786         Ptr->getOpcode() == X86ISD::WrapperRIP)
4787       Ptr = Ptr->getOperand(0);
4788
4789     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4790     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4791       return false;
4792
4793     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4794     if (C) {
4795       DecodeVPERMVMask(C, VT, Mask);
4796       if (Mask.empty())
4797         return false;
4798       break;
4799     }
4800     return false;
4801   }
4802   case X86ISD::VPERMV3: {
4803     IsUnary = false;
4804     SDValue MaskNode = N->getOperand(1);
4805     while (MaskNode->getOpcode() == ISD::BITCAST)
4806       MaskNode = MaskNode->getOperand(1);
4807
4808     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4809       // If we have a build-vector, then things are easy.
4810       assert(MaskNode.getSimpleValueType().isInteger() &&
4811              MaskNode.getSimpleValueType().getVectorNumElements() ==
4812              VT.getVectorNumElements());
4813
4814       SmallVector<uint64_t, 32> RawMask;
4815       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4816
4817       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4818         SDValue Op = MaskNode->getOperand(i);
4819         if (Op->getOpcode() == ISD::UNDEF)
4820           RawMask.push_back((uint64_t)SM_SentinelUndef);
4821         else {
4822           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4823           if (!CN)
4824             return false;
4825           APInt MaskElement = CN->getAPIntValue();
4826           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4827         }
4828       }
4829       DecodeVPERMV3Mask(RawMask, Mask);
4830       break;
4831     }
4832
4833     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4834     if (!MaskLoad)
4835       return false;
4836
4837     SDValue Ptr = MaskLoad->getBasePtr();
4838     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4839         Ptr->getOpcode() == X86ISD::WrapperRIP)
4840       Ptr = Ptr->getOperand(0);
4841
4842     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4843     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4844       return false;
4845
4846     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4847     if (C) {
4848       DecodeVPERMV3Mask(C, VT, Mask);
4849       if (Mask.empty())
4850         return false;
4851       break;
4852     }
4853     return false;
4854   }
4855   default: llvm_unreachable("unknown target shuffle node");
4856   }
4857
4858   // If we have a fake unary shuffle, the shuffle mask is spread across two
4859   // inputs that are actually the same node. Re-map the mask to always point
4860   // into the first input.
4861   if (IsFakeUnary)
4862     for (int &M : Mask)
4863       if (M >= (int)Mask.size())
4864         M -= Mask.size();
4865
4866   return true;
4867 }
4868
4869 /// Returns the scalar element that will make up the ith
4870 /// element of the result of the vector shuffle.
4871 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4872                                    unsigned Depth) {
4873   if (Depth == 6)
4874     return SDValue();  // Limit search depth.
4875
4876   SDValue V = SDValue(N, 0);
4877   EVT VT = V.getValueType();
4878   unsigned Opcode = V.getOpcode();
4879
4880   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4881   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4882     int Elt = SV->getMaskElt(Index);
4883
4884     if (Elt < 0)
4885       return DAG.getUNDEF(VT.getVectorElementType());
4886
4887     unsigned NumElems = VT.getVectorNumElements();
4888     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4889                                          : SV->getOperand(1);
4890     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4891   }
4892
4893   // Recurse into target specific vector shuffles to find scalars.
4894   if (isTargetShuffle(Opcode)) {
4895     MVT ShufVT = V.getSimpleValueType();
4896     unsigned NumElems = ShufVT.getVectorNumElements();
4897     SmallVector<int, 16> ShuffleMask;
4898     bool IsUnary;
4899
4900     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4901       return SDValue();
4902
4903     int Elt = ShuffleMask[Index];
4904     if (Elt < 0)
4905       return DAG.getUNDEF(ShufVT.getVectorElementType());
4906
4907     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4908                                          : N->getOperand(1);
4909     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4910                                Depth+1);
4911   }
4912
4913   // Actual nodes that may contain scalar elements
4914   if (Opcode == ISD::BITCAST) {
4915     V = V.getOperand(0);
4916     EVT SrcVT = V.getValueType();
4917     unsigned NumElems = VT.getVectorNumElements();
4918
4919     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4920       return SDValue();
4921   }
4922
4923   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4924     return (Index == 0) ? V.getOperand(0)
4925                         : DAG.getUNDEF(VT.getVectorElementType());
4926
4927   if (V.getOpcode() == ISD::BUILD_VECTOR)
4928     return V.getOperand(Index);
4929
4930   return SDValue();
4931 }
4932
4933 /// Custom lower build_vector of v16i8.
4934 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4935                                        unsigned NumNonZero, unsigned NumZero,
4936                                        SelectionDAG &DAG,
4937                                        const X86Subtarget* Subtarget,
4938                                        const TargetLowering &TLI) {
4939   if (NumNonZero > 8)
4940     return SDValue();
4941
4942   SDLoc dl(Op);
4943   SDValue V;
4944   bool First = true;
4945
4946   // SSE4.1 - use PINSRB to insert each byte directly.
4947   if (Subtarget->hasSSE41()) {
4948     for (unsigned i = 0; i < 16; ++i) {
4949       bool isNonZero = (NonZeros & (1 << i)) != 0;
4950       if (isNonZero) {
4951         if (First) {
4952           if (NumZero)
4953             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4954           else
4955             V = DAG.getUNDEF(MVT::v16i8);
4956           First = false;
4957         }
4958         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4959                         MVT::v16i8, V, Op.getOperand(i),
4960                         DAG.getIntPtrConstant(i, dl));
4961       }
4962     }
4963
4964     return V;
4965   }
4966
4967   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4968   for (unsigned i = 0; i < 16; ++i) {
4969     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4970     if (ThisIsNonZero && First) {
4971       if (NumZero)
4972         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4973       else
4974         V = DAG.getUNDEF(MVT::v8i16);
4975       First = false;
4976     }
4977
4978     if ((i & 1) != 0) {
4979       SDValue ThisElt, LastElt;
4980       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4981       if (LastIsNonZero) {
4982         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4983                               MVT::i16, Op.getOperand(i-1));
4984       }
4985       if (ThisIsNonZero) {
4986         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4987         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4988                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4989         if (LastIsNonZero)
4990           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4991       } else
4992         ThisElt = LastElt;
4993
4994       if (ThisElt.getNode())
4995         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4996                         DAG.getIntPtrConstant(i/2, dl));
4997     }
4998   }
4999
5000   return DAG.getBitcast(MVT::v16i8, V);
5001 }
5002
5003 /// Custom lower build_vector of v8i16.
5004 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5005                                      unsigned NumNonZero, unsigned NumZero,
5006                                      SelectionDAG &DAG,
5007                                      const X86Subtarget* Subtarget,
5008                                      const TargetLowering &TLI) {
5009   if (NumNonZero > 4)
5010     return SDValue();
5011
5012   SDLoc dl(Op);
5013   SDValue V;
5014   bool First = true;
5015   for (unsigned i = 0; i < 8; ++i) {
5016     bool isNonZero = (NonZeros & (1 << i)) != 0;
5017     if (isNonZero) {
5018       if (First) {
5019         if (NumZero)
5020           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5021         else
5022           V = DAG.getUNDEF(MVT::v8i16);
5023         First = false;
5024       }
5025       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5026                       MVT::v8i16, V, Op.getOperand(i),
5027                       DAG.getIntPtrConstant(i, dl));
5028     }
5029   }
5030
5031   return V;
5032 }
5033
5034 /// Custom lower build_vector of v4i32 or v4f32.
5035 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5036                                      const X86Subtarget *Subtarget,
5037                                      const TargetLowering &TLI) {
5038   // Find all zeroable elements.
5039   std::bitset<4> Zeroable;
5040   for (int i=0; i < 4; ++i) {
5041     SDValue Elt = Op->getOperand(i);
5042     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5043   }
5044   assert(Zeroable.size() - Zeroable.count() > 1 &&
5045          "We expect at least two non-zero elements!");
5046
5047   // We only know how to deal with build_vector nodes where elements are either
5048   // zeroable or extract_vector_elt with constant index.
5049   SDValue FirstNonZero;
5050   unsigned FirstNonZeroIdx;
5051   for (unsigned i=0; i < 4; ++i) {
5052     if (Zeroable[i])
5053       continue;
5054     SDValue Elt = Op->getOperand(i);
5055     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5056         !isa<ConstantSDNode>(Elt.getOperand(1)))
5057       return SDValue();
5058     // Make sure that this node is extracting from a 128-bit vector.
5059     MVT VT = Elt.getOperand(0).getSimpleValueType();
5060     if (!VT.is128BitVector())
5061       return SDValue();
5062     if (!FirstNonZero.getNode()) {
5063       FirstNonZero = Elt;
5064       FirstNonZeroIdx = i;
5065     }
5066   }
5067
5068   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5069   SDValue V1 = FirstNonZero.getOperand(0);
5070   MVT VT = V1.getSimpleValueType();
5071
5072   // See if this build_vector can be lowered as a blend with zero.
5073   SDValue Elt;
5074   unsigned EltMaskIdx, EltIdx;
5075   int Mask[4];
5076   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5077     if (Zeroable[EltIdx]) {
5078       // The zero vector will be on the right hand side.
5079       Mask[EltIdx] = EltIdx+4;
5080       continue;
5081     }
5082
5083     Elt = Op->getOperand(EltIdx);
5084     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5085     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5086     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5087       break;
5088     Mask[EltIdx] = EltIdx;
5089   }
5090
5091   if (EltIdx == 4) {
5092     // Let the shuffle legalizer deal with blend operations.
5093     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5094     if (V1.getSimpleValueType() != VT)
5095       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5096     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5097   }
5098
5099   // See if we can lower this build_vector to a INSERTPS.
5100   if (!Subtarget->hasSSE41())
5101     return SDValue();
5102
5103   SDValue V2 = Elt.getOperand(0);
5104   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5105     V1 = SDValue();
5106
5107   bool CanFold = true;
5108   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5109     if (Zeroable[i])
5110       continue;
5111
5112     SDValue Current = Op->getOperand(i);
5113     SDValue SrcVector = Current->getOperand(0);
5114     if (!V1.getNode())
5115       V1 = SrcVector;
5116     CanFold = SrcVector == V1 &&
5117       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5118   }
5119
5120   if (!CanFold)
5121     return SDValue();
5122
5123   assert(V1.getNode() && "Expected at least two non-zero elements!");
5124   if (V1.getSimpleValueType() != MVT::v4f32)
5125     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5126   if (V2.getSimpleValueType() != MVT::v4f32)
5127     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5128
5129   // Ok, we can emit an INSERTPS instruction.
5130   unsigned ZMask = Zeroable.to_ulong();
5131
5132   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5133   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5134   SDLoc DL(Op);
5135   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5136                                DAG.getIntPtrConstant(InsertPSMask, DL));
5137   return DAG.getBitcast(VT, Result);
5138 }
5139
5140 /// Return a vector logical shift node.
5141 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5142                          unsigned NumBits, SelectionDAG &DAG,
5143                          const TargetLowering &TLI, SDLoc dl) {
5144   assert(VT.is128BitVector() && "Unknown type for VShift");
5145   MVT ShVT = MVT::v2i64;
5146   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5147   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5148   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5149   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5150   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5151   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5152 }
5153
5154 static SDValue
5155 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5156
5157   // Check if the scalar load can be widened into a vector load. And if
5158   // the address is "base + cst" see if the cst can be "absorbed" into
5159   // the shuffle mask.
5160   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5161     SDValue Ptr = LD->getBasePtr();
5162     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5163       return SDValue();
5164     EVT PVT = LD->getValueType(0);
5165     if (PVT != MVT::i32 && PVT != MVT::f32)
5166       return SDValue();
5167
5168     int FI = -1;
5169     int64_t Offset = 0;
5170     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5171       FI = FINode->getIndex();
5172       Offset = 0;
5173     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5174                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5175       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5176       Offset = Ptr.getConstantOperandVal(1);
5177       Ptr = Ptr.getOperand(0);
5178     } else {
5179       return SDValue();
5180     }
5181
5182     // FIXME: 256-bit vector instructions don't require a strict alignment,
5183     // improve this code to support it better.
5184     unsigned RequiredAlign = VT.getSizeInBits()/8;
5185     SDValue Chain = LD->getChain();
5186     // Make sure the stack object alignment is at least 16 or 32.
5187     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5188     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5189       if (MFI->isFixedObjectIndex(FI)) {
5190         // Can't change the alignment. FIXME: It's possible to compute
5191         // the exact stack offset and reference FI + adjust offset instead.
5192         // If someone *really* cares about this. That's the way to implement it.
5193         return SDValue();
5194       } else {
5195         MFI->setObjectAlignment(FI, RequiredAlign);
5196       }
5197     }
5198
5199     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5200     // Ptr + (Offset & ~15).
5201     if (Offset < 0)
5202       return SDValue();
5203     if ((Offset % RequiredAlign) & 3)
5204       return SDValue();
5205     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5206     if (StartOffset) {
5207       SDLoc DL(Ptr);
5208       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5209                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5210     }
5211
5212     int EltNo = (Offset - StartOffset) >> 2;
5213     unsigned NumElems = VT.getVectorNumElements();
5214
5215     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5216     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5217                              LD->getPointerInfo().getWithOffset(StartOffset),
5218                              false, false, false, 0);
5219
5220     SmallVector<int, 8> Mask(NumElems, EltNo);
5221
5222     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5223   }
5224
5225   return SDValue();
5226 }
5227
5228 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5229 /// elements can be replaced by a single large load which has the same value as
5230 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5231 ///
5232 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5233 ///
5234 /// FIXME: we'd also like to handle the case where the last elements are zero
5235 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5236 /// There's even a handy isZeroNode for that purpose.
5237 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5238                                         SDLoc &DL, SelectionDAG &DAG,
5239                                         bool isAfterLegalize) {
5240   unsigned NumElems = Elts.size();
5241
5242   LoadSDNode *LDBase = nullptr;
5243   unsigned LastLoadedElt = -1U;
5244
5245   // For each element in the initializer, see if we've found a load or an undef.
5246   // If we don't find an initial load element, or later load elements are
5247   // non-consecutive, bail out.
5248   for (unsigned i = 0; i < NumElems; ++i) {
5249     SDValue Elt = Elts[i];
5250     // Look through a bitcast.
5251     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5252       Elt = Elt.getOperand(0);
5253     if (!Elt.getNode() ||
5254         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5255       return SDValue();
5256     if (!LDBase) {
5257       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5258         return SDValue();
5259       LDBase = cast<LoadSDNode>(Elt.getNode());
5260       LastLoadedElt = i;
5261       continue;
5262     }
5263     if (Elt.getOpcode() == ISD::UNDEF)
5264       continue;
5265
5266     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5267     EVT LdVT = Elt.getValueType();
5268     // Each loaded element must be the correct fractional portion of the
5269     // requested vector load.
5270     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5271       return SDValue();
5272     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5273       return SDValue();
5274     LastLoadedElt = i;
5275   }
5276
5277   // If we have found an entire vector of loads and undefs, then return a large
5278   // load of the entire vector width starting at the base pointer.  If we found
5279   // consecutive loads for the low half, generate a vzext_load node.
5280   if (LastLoadedElt == NumElems - 1) {
5281     assert(LDBase && "Did not find base load for merging consecutive loads");
5282     EVT EltVT = LDBase->getValueType(0);
5283     // Ensure that the input vector size for the merged loads matches the
5284     // cumulative size of the input elements.
5285     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5286       return SDValue();
5287
5288     if (isAfterLegalize &&
5289         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5290       return SDValue();
5291
5292     SDValue NewLd = SDValue();
5293
5294     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5295                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5296                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5297                         LDBase->getAlignment());
5298
5299     if (LDBase->hasAnyUseOfValue(1)) {
5300       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5301                                      SDValue(LDBase, 1),
5302                                      SDValue(NewLd.getNode(), 1));
5303       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5304       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5305                              SDValue(NewLd.getNode(), 1));
5306     }
5307
5308     return NewLd;
5309   }
5310
5311   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5312   //of a v4i32 / v4f32. It's probably worth generalizing.
5313   EVT EltVT = VT.getVectorElementType();
5314   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5315       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5316     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5317     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5318     SDValue ResNode =
5319         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5320                                 LDBase->getPointerInfo(),
5321                                 LDBase->getAlignment(),
5322                                 false/*isVolatile*/, true/*ReadMem*/,
5323                                 false/*WriteMem*/);
5324
5325     // Make sure the newly-created LOAD is in the same position as LDBase in
5326     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5327     // update uses of LDBase's output chain to use the TokenFactor.
5328     if (LDBase->hasAnyUseOfValue(1)) {
5329       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5330                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5331       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5332       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5333                              SDValue(ResNode.getNode(), 1));
5334     }
5335
5336     return DAG.getBitcast(VT, ResNode);
5337   }
5338   return SDValue();
5339 }
5340
5341 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5342 /// to generate a splat value for the following cases:
5343 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5344 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5345 /// a scalar load, or a constant.
5346 /// The VBROADCAST node is returned when a pattern is found,
5347 /// or SDValue() otherwise.
5348 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5349                                     SelectionDAG &DAG) {
5350   // VBROADCAST requires AVX.
5351   // TODO: Splats could be generated for non-AVX CPUs using SSE
5352   // instructions, but there's less potential gain for only 128-bit vectors.
5353   if (!Subtarget->hasAVX())
5354     return SDValue();
5355
5356   MVT VT = Op.getSimpleValueType();
5357   SDLoc dl(Op);
5358
5359   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5360          "Unsupported vector type for broadcast.");
5361
5362   SDValue Ld;
5363   bool ConstSplatVal;
5364
5365   switch (Op.getOpcode()) {
5366     default:
5367       // Unknown pattern found.
5368       return SDValue();
5369
5370     case ISD::BUILD_VECTOR: {
5371       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5372       BitVector UndefElements;
5373       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5374
5375       // We need a splat of a single value to use broadcast, and it doesn't
5376       // make any sense if the value is only in one element of the vector.
5377       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5378         return SDValue();
5379
5380       Ld = Splat;
5381       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5382                        Ld.getOpcode() == ISD::ConstantFP);
5383
5384       // Make sure that all of the users of a non-constant load are from the
5385       // BUILD_VECTOR node.
5386       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5387         return SDValue();
5388       break;
5389     }
5390
5391     case ISD::VECTOR_SHUFFLE: {
5392       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5393
5394       // Shuffles must have a splat mask where the first element is
5395       // broadcasted.
5396       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5397         return SDValue();
5398
5399       SDValue Sc = Op.getOperand(0);
5400       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5401           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5402
5403         if (!Subtarget->hasInt256())
5404           return SDValue();
5405
5406         // Use the register form of the broadcast instruction available on AVX2.
5407         if (VT.getSizeInBits() >= 256)
5408           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5409         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5410       }
5411
5412       Ld = Sc.getOperand(0);
5413       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5414                        Ld.getOpcode() == ISD::ConstantFP);
5415
5416       // The scalar_to_vector node and the suspected
5417       // load node must have exactly one user.
5418       // Constants may have multiple users.
5419
5420       // AVX-512 has register version of the broadcast
5421       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5422         Ld.getValueType().getSizeInBits() >= 32;
5423       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5424           !hasRegVer))
5425         return SDValue();
5426       break;
5427     }
5428   }
5429
5430   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5431   bool IsGE256 = (VT.getSizeInBits() >= 256);
5432
5433   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5434   // instruction to save 8 or more bytes of constant pool data.
5435   // TODO: If multiple splats are generated to load the same constant,
5436   // it may be detrimental to overall size. There needs to be a way to detect
5437   // that condition to know if this is truly a size win.
5438   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5439
5440   // Handle broadcasting a single constant scalar from the constant pool
5441   // into a vector.
5442   // On Sandybridge (no AVX2), it is still better to load a constant vector
5443   // from the constant pool and not to broadcast it from a scalar.
5444   // But override that restriction when optimizing for size.
5445   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5446   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5447     EVT CVT = Ld.getValueType();
5448     assert(!CVT.isVector() && "Must not broadcast a vector type");
5449
5450     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5451     // For size optimization, also splat v2f64 and v2i64, and for size opt
5452     // with AVX2, also splat i8 and i16.
5453     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5454     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5455         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5456       const Constant *C = nullptr;
5457       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5458         C = CI->getConstantIntValue();
5459       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5460         C = CF->getConstantFPValue();
5461
5462       assert(C && "Invalid constant type");
5463
5464       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5465       SDValue CP =
5466           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5467       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5468       Ld = DAG.getLoad(
5469           CVT, dl, DAG.getEntryNode(), CP,
5470           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5471           false, false, Alignment);
5472
5473       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5474     }
5475   }
5476
5477   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5478
5479   // Handle AVX2 in-register broadcasts.
5480   if (!IsLoad && Subtarget->hasInt256() &&
5481       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5482     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5483
5484   // The scalar source must be a normal load.
5485   if (!IsLoad)
5486     return SDValue();
5487
5488   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5489       (Subtarget->hasVLX() && ScalarSize == 64))
5490     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5491
5492   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5493   // double since there is no vbroadcastsd xmm
5494   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5495     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5496       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5497   }
5498
5499   // Unsupported broadcast.
5500   return SDValue();
5501 }
5502
5503 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5504 /// underlying vector and index.
5505 ///
5506 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5507 /// index.
5508 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5509                                          SDValue ExtIdx) {
5510   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5511   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5512     return Idx;
5513
5514   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5515   // lowered this:
5516   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5517   // to:
5518   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5519   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5520   //                           undef)
5521   //                       Constant<0>)
5522   // In this case the vector is the extract_subvector expression and the index
5523   // is 2, as specified by the shuffle.
5524   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5525   SDValue ShuffleVec = SVOp->getOperand(0);
5526   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5527   assert(ShuffleVecVT.getVectorElementType() ==
5528          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5529
5530   int ShuffleIdx = SVOp->getMaskElt(Idx);
5531   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5532     ExtractedFromVec = ShuffleVec;
5533     return ShuffleIdx;
5534   }
5535   return Idx;
5536 }
5537
5538 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5539   MVT VT = Op.getSimpleValueType();
5540
5541   // Skip if insert_vec_elt is not supported.
5542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5543   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5544     return SDValue();
5545
5546   SDLoc DL(Op);
5547   unsigned NumElems = Op.getNumOperands();
5548
5549   SDValue VecIn1;
5550   SDValue VecIn2;
5551   SmallVector<unsigned, 4> InsertIndices;
5552   SmallVector<int, 8> Mask(NumElems, -1);
5553
5554   for (unsigned i = 0; i != NumElems; ++i) {
5555     unsigned Opc = Op.getOperand(i).getOpcode();
5556
5557     if (Opc == ISD::UNDEF)
5558       continue;
5559
5560     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5561       // Quit if more than 1 elements need inserting.
5562       if (InsertIndices.size() > 1)
5563         return SDValue();
5564
5565       InsertIndices.push_back(i);
5566       continue;
5567     }
5568
5569     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5570     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5571     // Quit if non-constant index.
5572     if (!isa<ConstantSDNode>(ExtIdx))
5573       return SDValue();
5574     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5575
5576     // Quit if extracted from vector of different type.
5577     if (ExtractedFromVec.getValueType() != VT)
5578       return SDValue();
5579
5580     if (!VecIn1.getNode())
5581       VecIn1 = ExtractedFromVec;
5582     else if (VecIn1 != ExtractedFromVec) {
5583       if (!VecIn2.getNode())
5584         VecIn2 = ExtractedFromVec;
5585       else if (VecIn2 != ExtractedFromVec)
5586         // Quit if more than 2 vectors to shuffle
5587         return SDValue();
5588     }
5589
5590     if (ExtractedFromVec == VecIn1)
5591       Mask[i] = Idx;
5592     else if (ExtractedFromVec == VecIn2)
5593       Mask[i] = Idx + NumElems;
5594   }
5595
5596   if (!VecIn1.getNode())
5597     return SDValue();
5598
5599   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5600   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5601   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5602     unsigned Idx = InsertIndices[i];
5603     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5604                      DAG.getIntPtrConstant(Idx, DL));
5605   }
5606
5607   return NV;
5608 }
5609
5610 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5611   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5612          Op.getScalarValueSizeInBits() == 1 &&
5613          "Can not convert non-constant vector");
5614   uint64_t Immediate = 0;
5615   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5616     SDValue In = Op.getOperand(idx);
5617     if (In.getOpcode() != ISD::UNDEF)
5618       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5619   }
5620   SDLoc dl(Op);
5621   MVT VT =
5622    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5623   return DAG.getConstant(Immediate, dl, VT);
5624 }
5625 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5626 SDValue
5627 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5628
5629   MVT VT = Op.getSimpleValueType();
5630   assert((VT.getVectorElementType() == MVT::i1) &&
5631          "Unexpected type in LowerBUILD_VECTORvXi1!");
5632
5633   SDLoc dl(Op);
5634   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5635     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5636     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5637     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5638   }
5639
5640   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5641     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5642     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5643     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5644   }
5645
5646   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5647     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5648     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5649       return DAG.getBitcast(VT, Imm);
5650     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5651     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5652                         DAG.getIntPtrConstant(0, dl));
5653   }
5654
5655   // Vector has one or more non-const elements
5656   uint64_t Immediate = 0;
5657   SmallVector<unsigned, 16> NonConstIdx;
5658   bool IsSplat = true;
5659   bool HasConstElts = false;
5660   int SplatIdx = -1;
5661   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5662     SDValue In = Op.getOperand(idx);
5663     if (In.getOpcode() == ISD::UNDEF)
5664       continue;
5665     if (!isa<ConstantSDNode>(In))
5666       NonConstIdx.push_back(idx);
5667     else {
5668       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5669       HasConstElts = true;
5670     }
5671     if (SplatIdx == -1)
5672       SplatIdx = idx;
5673     else if (In != Op.getOperand(SplatIdx))
5674       IsSplat = false;
5675   }
5676
5677   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5678   if (IsSplat)
5679     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5680                        DAG.getConstant(1, dl, VT),
5681                        DAG.getConstant(0, dl, VT));
5682
5683   // insert elements one by one
5684   SDValue DstVec;
5685   SDValue Imm;
5686   if (Immediate) {
5687     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5688     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5689   }
5690   else if (HasConstElts)
5691     Imm = DAG.getConstant(0, dl, VT);
5692   else
5693     Imm = DAG.getUNDEF(VT);
5694   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5695     DstVec = DAG.getBitcast(VT, Imm);
5696   else {
5697     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5698     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5699                          DAG.getIntPtrConstant(0, dl));
5700   }
5701
5702   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5703     unsigned InsertIdx = NonConstIdx[i];
5704     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5705                          Op.getOperand(InsertIdx),
5706                          DAG.getIntPtrConstant(InsertIdx, dl));
5707   }
5708   return DstVec;
5709 }
5710
5711 /// \brief Return true if \p N implements a horizontal binop and return the
5712 /// operands for the horizontal binop into V0 and V1.
5713 ///
5714 /// This is a helper function of LowerToHorizontalOp().
5715 /// This function checks that the build_vector \p N in input implements a
5716 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5717 /// operation to match.
5718 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5719 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5720 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5721 /// arithmetic sub.
5722 ///
5723 /// This function only analyzes elements of \p N whose indices are
5724 /// in range [BaseIdx, LastIdx).
5725 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5726                               SelectionDAG &DAG,
5727                               unsigned BaseIdx, unsigned LastIdx,
5728                               SDValue &V0, SDValue &V1) {
5729   EVT VT = N->getValueType(0);
5730
5731   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5732   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5733          "Invalid Vector in input!");
5734
5735   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5736   bool CanFold = true;
5737   unsigned ExpectedVExtractIdx = BaseIdx;
5738   unsigned NumElts = LastIdx - BaseIdx;
5739   V0 = DAG.getUNDEF(VT);
5740   V1 = DAG.getUNDEF(VT);
5741
5742   // Check if N implements a horizontal binop.
5743   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5744     SDValue Op = N->getOperand(i + BaseIdx);
5745
5746     // Skip UNDEFs.
5747     if (Op->getOpcode() == ISD::UNDEF) {
5748       // Update the expected vector extract index.
5749       if (i * 2 == NumElts)
5750         ExpectedVExtractIdx = BaseIdx;
5751       ExpectedVExtractIdx += 2;
5752       continue;
5753     }
5754
5755     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5756
5757     if (!CanFold)
5758       break;
5759
5760     SDValue Op0 = Op.getOperand(0);
5761     SDValue Op1 = Op.getOperand(1);
5762
5763     // Try to match the following pattern:
5764     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5765     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5766         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5767         Op0.getOperand(0) == Op1.getOperand(0) &&
5768         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5769         isa<ConstantSDNode>(Op1.getOperand(1)));
5770     if (!CanFold)
5771       break;
5772
5773     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5774     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5775
5776     if (i * 2 < NumElts) {
5777       if (V0.getOpcode() == ISD::UNDEF) {
5778         V0 = Op0.getOperand(0);
5779         if (V0.getValueType() != VT)
5780           return false;
5781       }
5782     } else {
5783       if (V1.getOpcode() == ISD::UNDEF) {
5784         V1 = Op0.getOperand(0);
5785         if (V1.getValueType() != VT)
5786           return false;
5787       }
5788       if (i * 2 == NumElts)
5789         ExpectedVExtractIdx = BaseIdx;
5790     }
5791
5792     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5793     if (I0 == ExpectedVExtractIdx)
5794       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5795     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5796       // Try to match the following dag sequence:
5797       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5798       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5799     } else
5800       CanFold = false;
5801
5802     ExpectedVExtractIdx += 2;
5803   }
5804
5805   return CanFold;
5806 }
5807
5808 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5809 /// a concat_vector.
5810 ///
5811 /// This is a helper function of LowerToHorizontalOp().
5812 /// This function expects two 256-bit vectors called V0 and V1.
5813 /// At first, each vector is split into two separate 128-bit vectors.
5814 /// Then, the resulting 128-bit vectors are used to implement two
5815 /// horizontal binary operations.
5816 ///
5817 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5818 ///
5819 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5820 /// the two new horizontal binop.
5821 /// When Mode is set, the first horizontal binop dag node would take as input
5822 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5823 /// horizontal binop dag node would take as input the lower 128-bit of V1
5824 /// and the upper 128-bit of V1.
5825 ///   Example:
5826 ///     HADD V0_LO, V0_HI
5827 ///     HADD V1_LO, V1_HI
5828 ///
5829 /// Otherwise, the first horizontal binop dag node takes as input the lower
5830 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5831 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5832 ///   Example:
5833 ///     HADD V0_LO, V1_LO
5834 ///     HADD V0_HI, V1_HI
5835 ///
5836 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5837 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5838 /// the upper 128-bits of the result.
5839 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5840                                      SDLoc DL, SelectionDAG &DAG,
5841                                      unsigned X86Opcode, bool Mode,
5842                                      bool isUndefLO, bool isUndefHI) {
5843   EVT VT = V0.getValueType();
5844   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5845          "Invalid nodes in input!");
5846
5847   unsigned NumElts = VT.getVectorNumElements();
5848   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5849   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5850   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5851   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5852   EVT NewVT = V0_LO.getValueType();
5853
5854   SDValue LO = DAG.getUNDEF(NewVT);
5855   SDValue HI = DAG.getUNDEF(NewVT);
5856
5857   if (Mode) {
5858     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5859     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5860       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5861     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5862       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5863   } else {
5864     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5865     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5866                        V1_LO->getOpcode() != ISD::UNDEF))
5867       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5868
5869     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5870                        V1_HI->getOpcode() != ISD::UNDEF))
5871       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5872   }
5873
5874   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5875 }
5876
5877 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5878 /// node.
5879 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5880                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5881   MVT VT = BV->getSimpleValueType(0);
5882   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5883       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5884     return SDValue();
5885
5886   SDLoc DL(BV);
5887   unsigned NumElts = VT.getVectorNumElements();
5888   SDValue InVec0 = DAG.getUNDEF(VT);
5889   SDValue InVec1 = DAG.getUNDEF(VT);
5890
5891   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5892           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5893
5894   // Odd-numbered elements in the input build vector are obtained from
5895   // adding two integer/float elements.
5896   // Even-numbered elements in the input build vector are obtained from
5897   // subtracting two integer/float elements.
5898   unsigned ExpectedOpcode = ISD::FSUB;
5899   unsigned NextExpectedOpcode = ISD::FADD;
5900   bool AddFound = false;
5901   bool SubFound = false;
5902
5903   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5904     SDValue Op = BV->getOperand(i);
5905
5906     // Skip 'undef' values.
5907     unsigned Opcode = Op.getOpcode();
5908     if (Opcode == ISD::UNDEF) {
5909       std::swap(ExpectedOpcode, NextExpectedOpcode);
5910       continue;
5911     }
5912
5913     // Early exit if we found an unexpected opcode.
5914     if (Opcode != ExpectedOpcode)
5915       return SDValue();
5916
5917     SDValue Op0 = Op.getOperand(0);
5918     SDValue Op1 = Op.getOperand(1);
5919
5920     // Try to match the following pattern:
5921     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5922     // Early exit if we cannot match that sequence.
5923     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5924         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5925         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5926         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5927         Op0.getOperand(1) != Op1.getOperand(1))
5928       return SDValue();
5929
5930     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5931     if (I0 != i)
5932       return SDValue();
5933
5934     // We found a valid add/sub node. Update the information accordingly.
5935     if (i & 1)
5936       AddFound = true;
5937     else
5938       SubFound = true;
5939
5940     // Update InVec0 and InVec1.
5941     if (InVec0.getOpcode() == ISD::UNDEF) {
5942       InVec0 = Op0.getOperand(0);
5943       if (InVec0.getSimpleValueType() != VT)
5944         return SDValue();
5945     }
5946     if (InVec1.getOpcode() == ISD::UNDEF) {
5947       InVec1 = Op1.getOperand(0);
5948       if (InVec1.getSimpleValueType() != VT)
5949         return SDValue();
5950     }
5951
5952     // Make sure that operands in input to each add/sub node always
5953     // come from a same pair of vectors.
5954     if (InVec0 != Op0.getOperand(0)) {
5955       if (ExpectedOpcode == ISD::FSUB)
5956         return SDValue();
5957
5958       // FADD is commutable. Try to commute the operands
5959       // and then test again.
5960       std::swap(Op0, Op1);
5961       if (InVec0 != Op0.getOperand(0))
5962         return SDValue();
5963     }
5964
5965     if (InVec1 != Op1.getOperand(0))
5966       return SDValue();
5967
5968     // Update the pair of expected opcodes.
5969     std::swap(ExpectedOpcode, NextExpectedOpcode);
5970   }
5971
5972   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5973   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5974       InVec1.getOpcode() != ISD::UNDEF)
5975     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5976
5977   return SDValue();
5978 }
5979
5980 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5981 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5982                                    const X86Subtarget *Subtarget,
5983                                    SelectionDAG &DAG) {
5984   MVT VT = BV->getSimpleValueType(0);
5985   unsigned NumElts = VT.getVectorNumElements();
5986   unsigned NumUndefsLO = 0;
5987   unsigned NumUndefsHI = 0;
5988   unsigned Half = NumElts/2;
5989
5990   // Count the number of UNDEF operands in the build_vector in input.
5991   for (unsigned i = 0, e = Half; i != e; ++i)
5992     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5993       NumUndefsLO++;
5994
5995   for (unsigned i = Half, e = NumElts; i != e; ++i)
5996     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5997       NumUndefsHI++;
5998
5999   // Early exit if this is either a build_vector of all UNDEFs or all the
6000   // operands but one are UNDEF.
6001   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6002     return SDValue();
6003
6004   SDLoc DL(BV);
6005   SDValue InVec0, InVec1;
6006   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6007     // Try to match an SSE3 float HADD/HSUB.
6008     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6009       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6010
6011     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6012       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6013   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6014     // Try to match an SSSE3 integer HADD/HSUB.
6015     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6016       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6017
6018     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6019       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6020   }
6021
6022   if (!Subtarget->hasAVX())
6023     return SDValue();
6024
6025   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6026     // Try to match an AVX horizontal add/sub of packed single/double
6027     // precision floating point values from 256-bit vectors.
6028     SDValue InVec2, InVec3;
6029     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6030         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6031         ((InVec0.getOpcode() == ISD::UNDEF ||
6032           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6033         ((InVec1.getOpcode() == ISD::UNDEF ||
6034           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6035       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6036
6037     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6038         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6039         ((InVec0.getOpcode() == ISD::UNDEF ||
6040           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6041         ((InVec1.getOpcode() == ISD::UNDEF ||
6042           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6043       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6044   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6045     // Try to match an AVX2 horizontal add/sub of signed integers.
6046     SDValue InVec2, InVec3;
6047     unsigned X86Opcode;
6048     bool CanFold = true;
6049
6050     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6051         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6052         ((InVec0.getOpcode() == ISD::UNDEF ||
6053           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6054         ((InVec1.getOpcode() == ISD::UNDEF ||
6055           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6056       X86Opcode = X86ISD::HADD;
6057     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6058         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6059         ((InVec0.getOpcode() == ISD::UNDEF ||
6060           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6061         ((InVec1.getOpcode() == ISD::UNDEF ||
6062           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6063       X86Opcode = X86ISD::HSUB;
6064     else
6065       CanFold = false;
6066
6067     if (CanFold) {
6068       // Fold this build_vector into a single horizontal add/sub.
6069       // Do this only if the target has AVX2.
6070       if (Subtarget->hasAVX2())
6071         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6072
6073       // Do not try to expand this build_vector into a pair of horizontal
6074       // add/sub if we can emit a pair of scalar add/sub.
6075       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6076         return SDValue();
6077
6078       // Convert this build_vector into a pair of horizontal binop followed by
6079       // a concat vector.
6080       bool isUndefLO = NumUndefsLO == Half;
6081       bool isUndefHI = NumUndefsHI == Half;
6082       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6083                                    isUndefLO, isUndefHI);
6084     }
6085   }
6086
6087   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6088        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6089     unsigned X86Opcode;
6090     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6091       X86Opcode = X86ISD::HADD;
6092     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6093       X86Opcode = X86ISD::HSUB;
6094     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6095       X86Opcode = X86ISD::FHADD;
6096     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6097       X86Opcode = X86ISD::FHSUB;
6098     else
6099       return SDValue();
6100
6101     // Don't try to expand this build_vector into a pair of horizontal add/sub
6102     // if we can simply emit a pair of scalar add/sub.
6103     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6104       return SDValue();
6105
6106     // Convert this build_vector into two horizontal add/sub followed by
6107     // a concat vector.
6108     bool isUndefLO = NumUndefsLO == Half;
6109     bool isUndefHI = NumUndefsHI == Half;
6110     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6111                                  isUndefLO, isUndefHI);
6112   }
6113
6114   return SDValue();
6115 }
6116
6117 SDValue
6118 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6119   SDLoc dl(Op);
6120
6121   MVT VT = Op.getSimpleValueType();
6122   MVT ExtVT = VT.getVectorElementType();
6123   unsigned NumElems = Op.getNumOperands();
6124
6125   // Generate vectors for predicate vectors.
6126   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6127     return LowerBUILD_VECTORvXi1(Op, DAG);
6128
6129   // Vectors containing all zeros can be matched by pxor and xorps later
6130   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6131     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6132     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6133     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6134       return Op;
6135
6136     return getZeroVector(VT, Subtarget, DAG, dl);
6137   }
6138
6139   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6140   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6141   // vpcmpeqd on 256-bit vectors.
6142   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6143     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6144       return Op;
6145
6146     if (!VT.is512BitVector())
6147       return getOnesVector(VT, Subtarget, DAG, dl);
6148   }
6149
6150   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6151   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6152     return AddSub;
6153   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6154     return HorizontalOp;
6155   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6156     return Broadcast;
6157
6158   unsigned EVTBits = ExtVT.getSizeInBits();
6159
6160   unsigned NumZero  = 0;
6161   unsigned NumNonZero = 0;
6162   unsigned NonZeros = 0;
6163   bool IsAllConstants = true;
6164   SmallSet<SDValue, 8> Values;
6165   for (unsigned i = 0; i < NumElems; ++i) {
6166     SDValue Elt = Op.getOperand(i);
6167     if (Elt.getOpcode() == ISD::UNDEF)
6168       continue;
6169     Values.insert(Elt);
6170     if (Elt.getOpcode() != ISD::Constant &&
6171         Elt.getOpcode() != ISD::ConstantFP)
6172       IsAllConstants = false;
6173     if (X86::isZeroNode(Elt))
6174       NumZero++;
6175     else {
6176       NonZeros |= (1 << i);
6177       NumNonZero++;
6178     }
6179   }
6180
6181   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6182   if (NumNonZero == 0)
6183     return DAG.getUNDEF(VT);
6184
6185   // Special case for single non-zero, non-undef, element.
6186   if (NumNonZero == 1) {
6187     unsigned Idx = countTrailingZeros(NonZeros);
6188     SDValue Item = Op.getOperand(Idx);
6189
6190     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6191     // the value are obviously zero, truncate the value to i32 and do the
6192     // insertion that way.  Only do this if the value is non-constant or if the
6193     // value is a constant being inserted into element 0.  It is cheaper to do
6194     // a constant pool load than it is to do a movd + shuffle.
6195     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6196         (!IsAllConstants || Idx == 0)) {
6197       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6198         // Handle SSE only.
6199         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6200         MVT VecVT = MVT::v4i32;
6201
6202         // Truncate the value (which may itself be a constant) to i32, and
6203         // convert it to a vector with movd (S2V+shuffle to zero extend).
6204         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6205         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6206         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6207                                       Item, Idx * 2, true, Subtarget, DAG));
6208       }
6209     }
6210
6211     // If we have a constant or non-constant insertion into the low element of
6212     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6213     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6214     // depending on what the source datatype is.
6215     if (Idx == 0) {
6216       if (NumZero == 0)
6217         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6218
6219       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6220           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6221         if (VT.is512BitVector()) {
6222           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6223           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6224                              Item, DAG.getIntPtrConstant(0, dl));
6225         }
6226         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6227                "Expected an SSE value type!");
6228         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6229         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6230         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6231       }
6232
6233       // We can't directly insert an i8 or i16 into a vector, so zero extend
6234       // it to i32 first.
6235       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6236         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6237         if (VT.is256BitVector()) {
6238           if (Subtarget->hasAVX()) {
6239             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6240             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6241           } else {
6242             // Without AVX, we need to extend to a 128-bit vector and then
6243             // insert into the 256-bit vector.
6244             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6245             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6246             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6247           }
6248         } else {
6249           assert(VT.is128BitVector() && "Expected an SSE value type!");
6250           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6251           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6252         }
6253         return DAG.getBitcast(VT, Item);
6254       }
6255     }
6256
6257     // Is it a vector logical left shift?
6258     if (NumElems == 2 && Idx == 1 &&
6259         X86::isZeroNode(Op.getOperand(0)) &&
6260         !X86::isZeroNode(Op.getOperand(1))) {
6261       unsigned NumBits = VT.getSizeInBits();
6262       return getVShift(true, VT,
6263                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6264                                    VT, Op.getOperand(1)),
6265                        NumBits/2, DAG, *this, dl);
6266     }
6267
6268     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6269       return SDValue();
6270
6271     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6272     // is a non-constant being inserted into an element other than the low one,
6273     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6274     // movd/movss) to move this into the low element, then shuffle it into
6275     // place.
6276     if (EVTBits == 32) {
6277       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6278       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6279     }
6280   }
6281
6282   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6283   if (Values.size() == 1) {
6284     if (EVTBits == 32) {
6285       // Instead of a shuffle like this:
6286       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6287       // Check if it's possible to issue this instead.
6288       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6289       unsigned Idx = countTrailingZeros(NonZeros);
6290       SDValue Item = Op.getOperand(Idx);
6291       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6292         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6293     }
6294     return SDValue();
6295   }
6296
6297   // A vector full of immediates; various special cases are already
6298   // handled, so this is best done with a single constant-pool load.
6299   if (IsAllConstants)
6300     return SDValue();
6301
6302   // For AVX-length vectors, see if we can use a vector load to get all of the
6303   // elements, otherwise build the individual 128-bit pieces and use
6304   // shuffles to put them in place.
6305   if (VT.is256BitVector() || VT.is512BitVector()) {
6306     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6307
6308     // Check for a build vector of consecutive loads.
6309     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6310       return LD;
6311
6312     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6313
6314     // Build both the lower and upper subvector.
6315     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6316                                 makeArrayRef(&V[0], NumElems/2));
6317     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6318                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6319
6320     // Recreate the wider vector with the lower and upper part.
6321     if (VT.is256BitVector())
6322       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6323     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6324   }
6325
6326   // Let legalizer expand 2-wide build_vectors.
6327   if (EVTBits == 64) {
6328     if (NumNonZero == 1) {
6329       // One half is zero or undef.
6330       unsigned Idx = countTrailingZeros(NonZeros);
6331       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6332                                  Op.getOperand(Idx));
6333       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6334     }
6335     return SDValue();
6336   }
6337
6338   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6339   if (EVTBits == 8 && NumElems == 16)
6340     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6341                                         Subtarget, *this))
6342       return V;
6343
6344   if (EVTBits == 16 && NumElems == 8)
6345     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6346                                       Subtarget, *this))
6347       return V;
6348
6349   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6350   if (EVTBits == 32 && NumElems == 4)
6351     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6352       return V;
6353
6354   // If element VT is == 32 bits, turn it into a number of shuffles.
6355   SmallVector<SDValue, 8> V(NumElems);
6356   if (NumElems == 4 && NumZero > 0) {
6357     for (unsigned i = 0; i < 4; ++i) {
6358       bool isZero = !(NonZeros & (1 << i));
6359       if (isZero)
6360         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6361       else
6362         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6363     }
6364
6365     for (unsigned i = 0; i < 2; ++i) {
6366       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6367         default: break;
6368         case 0:
6369           V[i] = V[i*2];  // Must be a zero vector.
6370           break;
6371         case 1:
6372           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6373           break;
6374         case 2:
6375           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6376           break;
6377         case 3:
6378           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6379           break;
6380       }
6381     }
6382
6383     bool Reverse1 = (NonZeros & 0x3) == 2;
6384     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6385     int MaskVec[] = {
6386       Reverse1 ? 1 : 0,
6387       Reverse1 ? 0 : 1,
6388       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6389       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6390     };
6391     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6392   }
6393
6394   if (Values.size() > 1 && VT.is128BitVector()) {
6395     // Check for a build vector of consecutive loads.
6396     for (unsigned i = 0; i < NumElems; ++i)
6397       V[i] = Op.getOperand(i);
6398
6399     // Check for elements which are consecutive loads.
6400     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6401       return LD;
6402
6403     // Check for a build vector from mostly shuffle plus few inserting.
6404     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6405       return Sh;
6406
6407     // For SSE 4.1, use insertps to put the high elements into the low element.
6408     if (Subtarget->hasSSE41()) {
6409       SDValue Result;
6410       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6411         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6412       else
6413         Result = DAG.getUNDEF(VT);
6414
6415       for (unsigned i = 1; i < NumElems; ++i) {
6416         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6417         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6418                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6419       }
6420       return Result;
6421     }
6422
6423     // Otherwise, expand into a number of unpckl*, start by extending each of
6424     // our (non-undef) elements to the full vector width with the element in the
6425     // bottom slot of the vector (which generates no code for SSE).
6426     for (unsigned i = 0; i < NumElems; ++i) {
6427       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6428         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6429       else
6430         V[i] = DAG.getUNDEF(VT);
6431     }
6432
6433     // Next, we iteratively mix elements, e.g. for v4f32:
6434     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6435     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6436     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6437     unsigned EltStride = NumElems >> 1;
6438     while (EltStride != 0) {
6439       for (unsigned i = 0; i < EltStride; ++i) {
6440         // If V[i+EltStride] is undef and this is the first round of mixing,
6441         // then it is safe to just drop this shuffle: V[i] is already in the
6442         // right place, the one element (since it's the first round) being
6443         // inserted as undef can be dropped.  This isn't safe for successive
6444         // rounds because they will permute elements within both vectors.
6445         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6446             EltStride == NumElems/2)
6447           continue;
6448
6449         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6450       }
6451       EltStride >>= 1;
6452     }
6453     return V[0];
6454   }
6455   return SDValue();
6456 }
6457
6458 // 256-bit AVX can use the vinsertf128 instruction
6459 // to create 256-bit vectors from two other 128-bit ones.
6460 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6461   SDLoc dl(Op);
6462   MVT ResVT = Op.getSimpleValueType();
6463
6464   assert((ResVT.is256BitVector() ||
6465           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6466
6467   SDValue V1 = Op.getOperand(0);
6468   SDValue V2 = Op.getOperand(1);
6469   unsigned NumElems = ResVT.getVectorNumElements();
6470   if (ResVT.is256BitVector())
6471     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6472
6473   if (Op.getNumOperands() == 4) {
6474     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6475                                   ResVT.getVectorNumElements()/2);
6476     SDValue V3 = Op.getOperand(2);
6477     SDValue V4 = Op.getOperand(3);
6478     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6479       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6480   }
6481   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6482 }
6483
6484 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6485                                        const X86Subtarget *Subtarget,
6486                                        SelectionDAG & DAG) {
6487   SDLoc dl(Op);
6488   MVT ResVT = Op.getSimpleValueType();
6489   unsigned NumOfOperands = Op.getNumOperands();
6490
6491   assert(isPowerOf2_32(NumOfOperands) &&
6492          "Unexpected number of operands in CONCAT_VECTORS");
6493
6494   if (NumOfOperands > 2) {
6495     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6496                                   ResVT.getVectorNumElements()/2);
6497     SmallVector<SDValue, 2> Ops;
6498     for (unsigned i = 0; i < NumOfOperands/2; i++)
6499       Ops.push_back(Op.getOperand(i));
6500     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6501     Ops.clear();
6502     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6503       Ops.push_back(Op.getOperand(i));
6504     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6505     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6506   }
6507
6508   SDValue V1 = Op.getOperand(0);
6509   SDValue V2 = Op.getOperand(1);
6510   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6511   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6512
6513   if (IsZeroV1 && IsZeroV2)
6514     return getZeroVector(ResVT, Subtarget, DAG, dl);
6515
6516   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6517   SDValue Undef = DAG.getUNDEF(ResVT);
6518   unsigned NumElems = ResVT.getVectorNumElements();
6519   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6520
6521   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6522   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6523   if (IsZeroV1)
6524     return V2;
6525
6526   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6527   // Zero the upper bits of V1
6528   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6529   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6530   if (IsZeroV2)
6531     return V1;
6532   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6533 }
6534
6535 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6536                                    const X86Subtarget *Subtarget,
6537                                    SelectionDAG &DAG) {
6538   MVT VT = Op.getSimpleValueType();
6539   if (VT.getVectorElementType() == MVT::i1)
6540     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6541
6542   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6543          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6544           Op.getNumOperands() == 4)));
6545
6546   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6547   // from two other 128-bit ones.
6548
6549   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6550   return LowerAVXCONCAT_VECTORS(Op, DAG);
6551 }
6552
6553 //===----------------------------------------------------------------------===//
6554 // Vector shuffle lowering
6555 //
6556 // This is an experimental code path for lowering vector shuffles on x86. It is
6557 // designed to handle arbitrary vector shuffles and blends, gracefully
6558 // degrading performance as necessary. It works hard to recognize idiomatic
6559 // shuffles and lower them to optimal instruction patterns without leaving
6560 // a framework that allows reasonably efficient handling of all vector shuffle
6561 // patterns.
6562 //===----------------------------------------------------------------------===//
6563
6564 /// \brief Tiny helper function to identify a no-op mask.
6565 ///
6566 /// This is a somewhat boring predicate function. It checks whether the mask
6567 /// array input, which is assumed to be a single-input shuffle mask of the kind
6568 /// used by the X86 shuffle instructions (not a fully general
6569 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6570 /// in-place shuffle are 'no-op's.
6571 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6572   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6573     if (Mask[i] != -1 && Mask[i] != i)
6574       return false;
6575   return true;
6576 }
6577
6578 /// \brief Helper function to classify a mask as a single-input mask.
6579 ///
6580 /// This isn't a generic single-input test because in the vector shuffle
6581 /// lowering we canonicalize single inputs to be the first input operand. This
6582 /// means we can more quickly test for a single input by only checking whether
6583 /// an input from the second operand exists. We also assume that the size of
6584 /// mask corresponds to the size of the input vectors which isn't true in the
6585 /// fully general case.
6586 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6587   for (int M : Mask)
6588     if (M >= (int)Mask.size())
6589       return false;
6590   return true;
6591 }
6592
6593 /// \brief Test whether there are elements crossing 128-bit lanes in this
6594 /// shuffle mask.
6595 ///
6596 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6597 /// and we routinely test for these.
6598 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6599   int LaneSize = 128 / VT.getScalarSizeInBits();
6600   int Size = Mask.size();
6601   for (int i = 0; i < Size; ++i)
6602     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6603       return true;
6604   return false;
6605 }
6606
6607 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6608 ///
6609 /// This checks a shuffle mask to see if it is performing the same
6610 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6611 /// that it is also not lane-crossing. It may however involve a blend from the
6612 /// same lane of a second vector.
6613 ///
6614 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6615 /// non-trivial to compute in the face of undef lanes. The representation is
6616 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6617 /// entries from both V1 and V2 inputs to the wider mask.
6618 static bool
6619 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6620                                 SmallVectorImpl<int> &RepeatedMask) {
6621   int LaneSize = 128 / VT.getScalarSizeInBits();
6622   RepeatedMask.resize(LaneSize, -1);
6623   int Size = Mask.size();
6624   for (int i = 0; i < Size; ++i) {
6625     if (Mask[i] < 0)
6626       continue;
6627     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6628       // This entry crosses lanes, so there is no way to model this shuffle.
6629       return false;
6630
6631     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6632     if (RepeatedMask[i % LaneSize] == -1)
6633       // This is the first non-undef entry in this slot of a 128-bit lane.
6634       RepeatedMask[i % LaneSize] =
6635           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6636     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6637       // Found a mismatch with the repeated mask.
6638       return false;
6639   }
6640   return true;
6641 }
6642
6643 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6644 /// arguments.
6645 ///
6646 /// This is a fast way to test a shuffle mask against a fixed pattern:
6647 ///
6648 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6649 ///
6650 /// It returns true if the mask is exactly as wide as the argument list, and
6651 /// each element of the mask is either -1 (signifying undef) or the value given
6652 /// in the argument.
6653 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6654                                 ArrayRef<int> ExpectedMask) {
6655   if (Mask.size() != ExpectedMask.size())
6656     return false;
6657
6658   int Size = Mask.size();
6659
6660   // If the values are build vectors, we can look through them to find
6661   // equivalent inputs that make the shuffles equivalent.
6662   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6663   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6664
6665   for (int i = 0; i < Size; ++i)
6666     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6667       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6668       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6669       if (!MaskBV || !ExpectedBV ||
6670           MaskBV->getOperand(Mask[i] % Size) !=
6671               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6672         return false;
6673     }
6674
6675   return true;
6676 }
6677
6678 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6679 ///
6680 /// This helper function produces an 8-bit shuffle immediate corresponding to
6681 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6682 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6683 /// example.
6684 ///
6685 /// NB: We rely heavily on "undef" masks preserving the input lane.
6686 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6687                                           SelectionDAG &DAG) {
6688   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6689   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6690   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6691   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6692   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6693
6694   unsigned Imm = 0;
6695   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6696   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6697   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6698   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6699   return DAG.getConstant(Imm, DL, MVT::i8);
6700 }
6701
6702 /// \brief Compute whether each element of a shuffle is zeroable.
6703 ///
6704 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6705 /// Either it is an undef element in the shuffle mask, the element of the input
6706 /// referenced is undef, or the element of the input referenced is known to be
6707 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6708 /// as many lanes with this technique as possible to simplify the remaining
6709 /// shuffle.
6710 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6711                                                      SDValue V1, SDValue V2) {
6712   SmallBitVector Zeroable(Mask.size(), false);
6713
6714   while (V1.getOpcode() == ISD::BITCAST)
6715     V1 = V1->getOperand(0);
6716   while (V2.getOpcode() == ISD::BITCAST)
6717     V2 = V2->getOperand(0);
6718
6719   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6720   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6721
6722   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6723     int M = Mask[i];
6724     // Handle the easy cases.
6725     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6726       Zeroable[i] = true;
6727       continue;
6728     }
6729
6730     // If this is an index into a build_vector node (which has the same number
6731     // of elements), dig out the input value and use it.
6732     SDValue V = M < Size ? V1 : V2;
6733     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6734       continue;
6735
6736     SDValue Input = V.getOperand(M % Size);
6737     // The UNDEF opcode check really should be dead code here, but not quite
6738     // worth asserting on (it isn't invalid, just unexpected).
6739     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6740       Zeroable[i] = true;
6741   }
6742
6743   return Zeroable;
6744 }
6745
6746 // X86 has dedicated unpack instructions that can handle specific blend
6747 // operations: UNPCKH and UNPCKL.
6748 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6749                                            SDValue V1, SDValue V2,
6750                                            SelectionDAG &DAG) {
6751   int NumElts = VT.getVectorNumElements();
6752   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6753   SmallVector<int, 8> Unpckl;
6754   SmallVector<int, 8> Unpckh;
6755
6756   for (int i = 0; i < NumElts; ++i) {
6757     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6758     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6759     int HiPos = LoPos + NumEltsInLane / 2;
6760     Unpckl.push_back(LoPos);
6761     Unpckh.push_back(HiPos);
6762   }
6763
6764   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6765     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6766   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6767     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6768
6769   // Commute and try again.
6770   ShuffleVectorSDNode::commuteMask(Unpckl);
6771   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6772     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6773
6774   ShuffleVectorSDNode::commuteMask(Unpckh);
6775   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6776     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6777
6778   return SDValue();
6779 }
6780
6781 /// \brief Try to emit a bitmask instruction for a shuffle.
6782 ///
6783 /// This handles cases where we can model a blend exactly as a bitmask due to
6784 /// one of the inputs being zeroable.
6785 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6786                                            SDValue V2, ArrayRef<int> Mask,
6787                                            SelectionDAG &DAG) {
6788   MVT EltVT = VT.getVectorElementType();
6789   int NumEltBits = EltVT.getSizeInBits();
6790   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6791   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6792   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6793                                     IntEltVT);
6794   if (EltVT.isFloatingPoint()) {
6795     Zero = DAG.getBitcast(EltVT, Zero);
6796     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6797   }
6798   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6799   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6800   SDValue V;
6801   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6802     if (Zeroable[i])
6803       continue;
6804     if (Mask[i] % Size != i)
6805       return SDValue(); // Not a blend.
6806     if (!V)
6807       V = Mask[i] < Size ? V1 : V2;
6808     else if (V != (Mask[i] < Size ? V1 : V2))
6809       return SDValue(); // Can only let one input through the mask.
6810
6811     VMaskOps[i] = AllOnes;
6812   }
6813   if (!V)
6814     return SDValue(); // No non-zeroable elements!
6815
6816   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6817   V = DAG.getNode(VT.isFloatingPoint()
6818                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6819                   DL, VT, V, VMask);
6820   return V;
6821 }
6822
6823 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6824 ///
6825 /// This is used as a fallback approach when first class blend instructions are
6826 /// unavailable. Currently it is only suitable for integer vectors, but could
6827 /// be generalized for floating point vectors if desirable.
6828 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6829                                             SDValue V2, ArrayRef<int> Mask,
6830                                             SelectionDAG &DAG) {
6831   assert(VT.isInteger() && "Only supports integer vector types!");
6832   MVT EltVT = VT.getVectorElementType();
6833   int NumEltBits = EltVT.getSizeInBits();
6834   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6835   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6836                                     EltVT);
6837   SmallVector<SDValue, 16> MaskOps;
6838   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6839     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6840       return SDValue(); // Shuffled input!
6841     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6842   }
6843
6844   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6845   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6846   // We have to cast V2 around.
6847   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6848   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6849                                       DAG.getBitcast(MaskVT, V1Mask),
6850                                       DAG.getBitcast(MaskVT, V2)));
6851   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6852 }
6853
6854 /// \brief Try to emit a blend instruction for a shuffle.
6855 ///
6856 /// This doesn't do any checks for the availability of instructions for blending
6857 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6858 /// be matched in the backend with the type given. What it does check for is
6859 /// that the shuffle mask is a blend, or convertible into a blend with zero.
6860 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6861                                          SDValue V2, ArrayRef<int> Original,
6862                                          const X86Subtarget *Subtarget,
6863                                          SelectionDAG &DAG) {
6864   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6865   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6866   SmallVector<int, 8> Mask(Original.begin(), Original.end());
6867   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6868   bool ForceV1Zero = false, ForceV2Zero = false;
6869
6870   // Attempt to generate the binary blend mask. If an input is zero then
6871   // we can use any lane.
6872   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
6873   unsigned BlendMask = 0;
6874   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6875     int M = Mask[i];
6876     if (M < 0)
6877       continue;
6878     if (M == i)
6879       continue;
6880     if (M == i + Size) {
6881       BlendMask |= 1u << i;
6882       continue;
6883     }
6884     if (Zeroable[i]) {
6885       if (V1IsZero) {
6886         ForceV1Zero = true;
6887         Mask[i] = i;
6888         continue;
6889       }
6890       if (V2IsZero) {
6891         ForceV2Zero = true;
6892         BlendMask |= 1u << i;
6893         Mask[i] = i + Size;
6894         continue;
6895       }
6896     }
6897     return SDValue(); // Shuffled input!
6898   }
6899
6900   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
6901   if (ForceV1Zero)
6902     V1 = getZeroVector(VT, Subtarget, DAG, DL);
6903   if (ForceV2Zero)
6904     V2 = getZeroVector(VT, Subtarget, DAG, DL);
6905
6906   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
6907     unsigned ScaledMask = 0;
6908     for (int i = 0; i != Size; ++i)
6909       if (BlendMask & (1u << i))
6910         for (int j = 0; j != Scale; ++j)
6911           ScaledMask |= 1u << (i * Scale + j);
6912     return ScaledMask;
6913   };
6914
6915   switch (VT.SimpleTy) {
6916   case MVT::v2f64:
6917   case MVT::v4f32:
6918   case MVT::v4f64:
6919   case MVT::v8f32:
6920     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6921                        DAG.getConstant(BlendMask, DL, MVT::i8));
6922
6923   case MVT::v4i64:
6924   case MVT::v8i32:
6925     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6926     // FALLTHROUGH
6927   case MVT::v2i64:
6928   case MVT::v4i32:
6929     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6930     // that instruction.
6931     if (Subtarget->hasAVX2()) {
6932       // Scale the blend by the number of 32-bit dwords per element.
6933       int Scale =  VT.getScalarSizeInBits() / 32;
6934       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6935       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6936       V1 = DAG.getBitcast(BlendVT, V1);
6937       V2 = DAG.getBitcast(BlendVT, V2);
6938       return DAG.getBitcast(
6939           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6940                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6941     }
6942     // FALLTHROUGH
6943   case MVT::v8i16: {
6944     // For integer shuffles we need to expand the mask and cast the inputs to
6945     // v8i16s prior to blending.
6946     int Scale = 8 / VT.getVectorNumElements();
6947     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6948     V1 = DAG.getBitcast(MVT::v8i16, V1);
6949     V2 = DAG.getBitcast(MVT::v8i16, V2);
6950     return DAG.getBitcast(VT,
6951                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6952                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6953   }
6954
6955   case MVT::v16i16: {
6956     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6957     SmallVector<int, 8> RepeatedMask;
6958     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6959       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6960       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6961       BlendMask = 0;
6962       for (int i = 0; i < 8; ++i)
6963         if (RepeatedMask[i] >= 16)
6964           BlendMask |= 1u << i;
6965       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6966                          DAG.getConstant(BlendMask, DL, MVT::i8));
6967     }
6968   }
6969     // FALLTHROUGH
6970   case MVT::v16i8:
6971   case MVT::v32i8: {
6972     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
6973            "256-bit byte-blends require AVX2 support!");
6974
6975     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6976     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6977       return Masked;
6978
6979     // Scale the blend by the number of bytes per element.
6980     int Scale = VT.getScalarSizeInBits() / 8;
6981
6982     // This form of blend is always done on bytes. Compute the byte vector
6983     // type.
6984     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6985
6986     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6987     // mix of LLVM's code generator and the x86 backend. We tell the code
6988     // generator that boolean values in the elements of an x86 vector register
6989     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6990     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6991     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6992     // of the element (the remaining are ignored) and 0 in that high bit would
6993     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6994     // the LLVM model for boolean values in vector elements gets the relevant
6995     // bit set, it is set backwards and over constrained relative to x86's
6996     // actual model.
6997     SmallVector<SDValue, 32> VSELECTMask;
6998     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6999       for (int j = 0; j < Scale; ++j)
7000         VSELECTMask.push_back(
7001             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7002                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7003                                           MVT::i8));
7004
7005     V1 = DAG.getBitcast(BlendVT, V1);
7006     V2 = DAG.getBitcast(BlendVT, V2);
7007     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7008                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7009                                                       BlendVT, VSELECTMask),
7010                                           V1, V2));
7011   }
7012
7013   default:
7014     llvm_unreachable("Not a supported integer vector type!");
7015   }
7016 }
7017
7018 /// \brief Try to lower as a blend of elements from two inputs followed by
7019 /// a single-input permutation.
7020 ///
7021 /// This matches the pattern where we can blend elements from two inputs and
7022 /// then reduce the shuffle to a single-input permutation.
7023 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7024                                                    SDValue V2,
7025                                                    ArrayRef<int> Mask,
7026                                                    SelectionDAG &DAG) {
7027   // We build up the blend mask while checking whether a blend is a viable way
7028   // to reduce the shuffle.
7029   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7030   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7031
7032   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7033     if (Mask[i] < 0)
7034       continue;
7035
7036     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7037
7038     if (BlendMask[Mask[i] % Size] == -1)
7039       BlendMask[Mask[i] % Size] = Mask[i];
7040     else if (BlendMask[Mask[i] % Size] != Mask[i])
7041       return SDValue(); // Can't blend in the needed input!
7042
7043     PermuteMask[i] = Mask[i] % Size;
7044   }
7045
7046   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7047   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7048 }
7049
7050 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7051 /// blends and permutes.
7052 ///
7053 /// This matches the extremely common pattern for handling combined
7054 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7055 /// operations. It will try to pick the best arrangement of shuffles and
7056 /// blends.
7057 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7058                                                           SDValue V1,
7059                                                           SDValue V2,
7060                                                           ArrayRef<int> Mask,
7061                                                           SelectionDAG &DAG) {
7062   // Shuffle the input elements into the desired positions in V1 and V2 and
7063   // blend them together.
7064   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7065   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7066   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7067   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7068     if (Mask[i] >= 0 && Mask[i] < Size) {
7069       V1Mask[i] = Mask[i];
7070       BlendMask[i] = i;
7071     } else if (Mask[i] >= Size) {
7072       V2Mask[i] = Mask[i] - Size;
7073       BlendMask[i] = i + Size;
7074     }
7075
7076   // Try to lower with the simpler initial blend strategy unless one of the
7077   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7078   // shuffle may be able to fold with a load or other benefit. However, when
7079   // we'll have to do 2x as many shuffles in order to achieve this, blending
7080   // first is a better strategy.
7081   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7082     if (SDValue BlendPerm =
7083             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7084       return BlendPerm;
7085
7086   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7087   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7088   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7089 }
7090
7091 /// \brief Try to lower a vector shuffle as a byte rotation.
7092 ///
7093 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7094 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7095 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7096 /// try to generically lower a vector shuffle through such an pattern. It
7097 /// does not check for the profitability of lowering either as PALIGNR or
7098 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7099 /// This matches shuffle vectors that look like:
7100 ///
7101 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7102 ///
7103 /// Essentially it concatenates V1 and V2, shifts right by some number of
7104 /// elements, and takes the low elements as the result. Note that while this is
7105 /// specified as a *right shift* because x86 is little-endian, it is a *left
7106 /// rotate* of the vector lanes.
7107 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7108                                               SDValue V2,
7109                                               ArrayRef<int> Mask,
7110                                               const X86Subtarget *Subtarget,
7111                                               SelectionDAG &DAG) {
7112   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7113
7114   int NumElts = Mask.size();
7115   int NumLanes = VT.getSizeInBits() / 128;
7116   int NumLaneElts = NumElts / NumLanes;
7117
7118   // We need to detect various ways of spelling a rotation:
7119   //   [11, 12, 13, 14, 15,  0,  1,  2]
7120   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7121   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7122   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7123   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7124   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7125   int Rotation = 0;
7126   SDValue Lo, Hi;
7127   for (int l = 0; l < NumElts; l += NumLaneElts) {
7128     for (int i = 0; i < NumLaneElts; ++i) {
7129       if (Mask[l + i] == -1)
7130         continue;
7131       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7132
7133       // Get the mod-Size index and lane correct it.
7134       int LaneIdx = (Mask[l + i] % NumElts) - l;
7135       // Make sure it was in this lane.
7136       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7137         return SDValue();
7138
7139       // Determine where a rotated vector would have started.
7140       int StartIdx = i - LaneIdx;
7141       if (StartIdx == 0)
7142         // The identity rotation isn't interesting, stop.
7143         return SDValue();
7144
7145       // If we found the tail of a vector the rotation must be the missing
7146       // front. If we found the head of a vector, it must be how much of the
7147       // head.
7148       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7149
7150       if (Rotation == 0)
7151         Rotation = CandidateRotation;
7152       else if (Rotation != CandidateRotation)
7153         // The rotations don't match, so we can't match this mask.
7154         return SDValue();
7155
7156       // Compute which value this mask is pointing at.
7157       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7158
7159       // Compute which of the two target values this index should be assigned
7160       // to. This reflects whether the high elements are remaining or the low
7161       // elements are remaining.
7162       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7163
7164       // Either set up this value if we've not encountered it before, or check
7165       // that it remains consistent.
7166       if (!TargetV)
7167         TargetV = MaskV;
7168       else if (TargetV != MaskV)
7169         // This may be a rotation, but it pulls from the inputs in some
7170         // unsupported interleaving.
7171         return SDValue();
7172     }
7173   }
7174
7175   // Check that we successfully analyzed the mask, and normalize the results.
7176   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7177   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7178   if (!Lo)
7179     Lo = Hi;
7180   else if (!Hi)
7181     Hi = Lo;
7182
7183   // The actual rotate instruction rotates bytes, so we need to scale the
7184   // rotation based on how many bytes are in the vector lane.
7185   int Scale = 16 / NumLaneElts;
7186
7187   // SSSE3 targets can use the palignr instruction.
7188   if (Subtarget->hasSSSE3()) {
7189     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7190     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7191     Lo = DAG.getBitcast(AlignVT, Lo);
7192     Hi = DAG.getBitcast(AlignVT, Hi);
7193
7194     return DAG.getBitcast(
7195         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7196                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7197   }
7198
7199   assert(VT.is128BitVector() &&
7200          "Rotate-based lowering only supports 128-bit lowering!");
7201   assert(Mask.size() <= 16 &&
7202          "Can shuffle at most 16 bytes in a 128-bit vector!");
7203
7204   // Default SSE2 implementation
7205   int LoByteShift = 16 - Rotation * Scale;
7206   int HiByteShift = Rotation * Scale;
7207
7208   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7209   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7210   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7211
7212   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7213                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7214   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7215                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7216   return DAG.getBitcast(VT,
7217                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7218 }
7219
7220 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7221 ///
7222 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7223 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7224 /// matches elements from one of the input vectors shuffled to the left or
7225 /// right with zeroable elements 'shifted in'. It handles both the strictly
7226 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7227 /// quad word lane.
7228 ///
7229 /// PSHL : (little-endian) left bit shift.
7230 /// [ zz, 0, zz,  2 ]
7231 /// [ -1, 4, zz, -1 ]
7232 /// PSRL : (little-endian) right bit shift.
7233 /// [  1, zz,  3, zz]
7234 /// [ -1, -1,  7, zz]
7235 /// PSLLDQ : (little-endian) left byte shift
7236 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7237 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7238 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7239 /// PSRLDQ : (little-endian) right byte shift
7240 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7241 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7242 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7243 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7244                                          SDValue V2, ArrayRef<int> Mask,
7245                                          SelectionDAG &DAG) {
7246   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7247
7248   int Size = Mask.size();
7249   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7250
7251   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7252     for (int i = 0; i < Size; i += Scale)
7253       for (int j = 0; j < Shift; ++j)
7254         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7255           return false;
7256
7257     return true;
7258   };
7259
7260   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7261     for (int i = 0; i != Size; i += Scale) {
7262       unsigned Pos = Left ? i + Shift : i;
7263       unsigned Low = Left ? i : i + Shift;
7264       unsigned Len = Scale - Shift;
7265       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7266                                       Low + (V == V1 ? 0 : Size)))
7267         return SDValue();
7268     }
7269
7270     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7271     bool ByteShift = ShiftEltBits > 64;
7272     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7273                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7274     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7275
7276     // Normalize the scale for byte shifts to still produce an i64 element
7277     // type.
7278     Scale = ByteShift ? Scale / 2 : Scale;
7279
7280     // We need to round trip through the appropriate type for the shift.
7281     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7282     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7283     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7284            "Illegal integer vector type");
7285     V = DAG.getBitcast(ShiftVT, V);
7286
7287     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7288                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7289     return DAG.getBitcast(VT, V);
7290   };
7291
7292   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7293   // keep doubling the size of the integer elements up to that. We can
7294   // then shift the elements of the integer vector by whole multiples of
7295   // their width within the elements of the larger integer vector. Test each
7296   // multiple to see if we can find a match with the moved element indices
7297   // and that the shifted in elements are all zeroable.
7298   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7299     for (int Shift = 1; Shift != Scale; ++Shift)
7300       for (bool Left : {true, false})
7301         if (CheckZeros(Shift, Scale, Left))
7302           for (SDValue V : {V1, V2})
7303             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7304               return Match;
7305
7306   // no match
7307   return SDValue();
7308 }
7309
7310 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7311 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7312                                            SDValue V2, ArrayRef<int> Mask,
7313                                            SelectionDAG &DAG) {
7314   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7315   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7316
7317   int Size = Mask.size();
7318   int HalfSize = Size / 2;
7319   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7320
7321   // Upper half must be undefined.
7322   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7323     return SDValue();
7324
7325   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7326   // Remainder of lower half result is zero and upper half is all undef.
7327   auto LowerAsEXTRQ = [&]() {
7328     // Determine the extraction length from the part of the
7329     // lower half that isn't zeroable.
7330     int Len = HalfSize;
7331     for (; Len > 0; --Len)
7332       if (!Zeroable[Len - 1])
7333         break;
7334     assert(Len > 0 && "Zeroable shuffle mask");
7335
7336     // Attempt to match first Len sequential elements from the lower half.
7337     SDValue Src;
7338     int Idx = -1;
7339     for (int i = 0; i != Len; ++i) {
7340       int M = Mask[i];
7341       if (M < 0)
7342         continue;
7343       SDValue &V = (M < Size ? V1 : V2);
7344       M = M % Size;
7345
7346       // All mask elements must be in the lower half.
7347       if (M >= HalfSize)
7348         return SDValue();
7349
7350       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7351         Src = V;
7352         Idx = M - i;
7353         continue;
7354       }
7355       return SDValue();
7356     }
7357
7358     if (Idx < 0)
7359       return SDValue();
7360
7361     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7362     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7363     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7364     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7365                        DAG.getConstant(BitLen, DL, MVT::i8),
7366                        DAG.getConstant(BitIdx, DL, MVT::i8));
7367   };
7368
7369   if (SDValue ExtrQ = LowerAsEXTRQ())
7370     return ExtrQ;
7371
7372   // INSERTQ: Extract lowest Len elements from lower half of second source and
7373   // insert over first source, starting at Idx.
7374   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7375   auto LowerAsInsertQ = [&]() {
7376     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7377       SDValue Base;
7378
7379       // Attempt to match first source from mask before insertion point.
7380       if (isUndefInRange(Mask, 0, Idx)) {
7381         /* EMPTY */
7382       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7383         Base = V1;
7384       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7385         Base = V2;
7386       } else {
7387         continue;
7388       }
7389
7390       // Extend the extraction length looking to match both the insertion of
7391       // the second source and the remaining elements of the first.
7392       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7393         SDValue Insert;
7394         int Len = Hi - Idx;
7395
7396         // Match insertion.
7397         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7398           Insert = V1;
7399         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7400           Insert = V2;
7401         } else {
7402           continue;
7403         }
7404
7405         // Match the remaining elements of the lower half.
7406         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7407           /* EMPTY */
7408         } else if ((!Base || (Base == V1)) &&
7409                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7410           Base = V1;
7411         } else if ((!Base || (Base == V2)) &&
7412                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7413                                               Size + Hi)) {
7414           Base = V2;
7415         } else {
7416           continue;
7417         }
7418
7419         // We may not have a base (first source) - this can safely be undefined.
7420         if (!Base)
7421           Base = DAG.getUNDEF(VT);
7422
7423         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7424         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7425         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7426                            DAG.getConstant(BitLen, DL, MVT::i8),
7427                            DAG.getConstant(BitIdx, DL, MVT::i8));
7428       }
7429     }
7430
7431     return SDValue();
7432   };
7433
7434   if (SDValue InsertQ = LowerAsInsertQ())
7435     return InsertQ;
7436
7437   return SDValue();
7438 }
7439
7440 /// \brief Lower a vector shuffle as a zero or any extension.
7441 ///
7442 /// Given a specific number of elements, element bit width, and extension
7443 /// stride, produce either a zero or any extension based on the available
7444 /// features of the subtarget. The extended elements are consecutive and
7445 /// begin and can start from an offseted element index in the input; to
7446 /// avoid excess shuffling the offset must either being in the bottom lane
7447 /// or at the start of a higher lane. All extended elements must be from
7448 /// the same lane.
7449 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7450     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7451     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7452   assert(Scale > 1 && "Need a scale to extend.");
7453   int EltBits = VT.getScalarSizeInBits();
7454   int NumElements = VT.getVectorNumElements();
7455   int NumEltsPerLane = 128 / EltBits;
7456   int OffsetLane = Offset / NumEltsPerLane;
7457   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7458          "Only 8, 16, and 32 bit elements can be extended.");
7459   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7460   assert(0 <= Offset && "Extension offset must be positive.");
7461   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7462          "Extension offset must be in the first lane or start an upper lane.");
7463
7464   // Check that an index is in same lane as the base offset.
7465   auto SafeOffset = [&](int Idx) {
7466     return OffsetLane == (Idx / NumEltsPerLane);
7467   };
7468
7469   // Shift along an input so that the offset base moves to the first element.
7470   auto ShuffleOffset = [&](SDValue V) {
7471     if (!Offset)
7472       return V;
7473
7474     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7475     for (int i = 0; i * Scale < NumElements; ++i) {
7476       int SrcIdx = i + Offset;
7477       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7478     }
7479     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7480   };
7481
7482   // Found a valid zext mask! Try various lowering strategies based on the
7483   // input type and available ISA extensions.
7484   if (Subtarget->hasSSE41()) {
7485     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7486     // PUNPCK will catch this in a later shuffle match.
7487     if (Offset && Scale == 2 && VT.is128BitVector())
7488       return SDValue();
7489     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7490                                  NumElements / Scale);
7491     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7492     return DAG.getBitcast(VT, InputV);
7493   }
7494
7495   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7496
7497   // For any extends we can cheat for larger element sizes and use shuffle
7498   // instructions that can fold with a load and/or copy.
7499   if (AnyExt && EltBits == 32) {
7500     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7501                          -1};
7502     return DAG.getBitcast(
7503         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7504                         DAG.getBitcast(MVT::v4i32, InputV),
7505                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7506   }
7507   if (AnyExt && EltBits == 16 && Scale > 2) {
7508     int PSHUFDMask[4] = {Offset / 2, -1,
7509                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7510     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7511                          DAG.getBitcast(MVT::v4i32, InputV),
7512                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7513     int PSHUFWMask[4] = {1, -1, -1, -1};
7514     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7515     return DAG.getBitcast(
7516         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7517                         DAG.getBitcast(MVT::v8i16, InputV),
7518                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7519   }
7520
7521   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7522   // to 64-bits.
7523   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7524     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7525     assert(VT.is128BitVector() && "Unexpected vector width!");
7526
7527     int LoIdx = Offset * EltBits;
7528     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7529                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7530                                          DAG.getConstant(EltBits, DL, MVT::i8),
7531                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7532
7533     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7534         !SafeOffset(Offset + 1))
7535       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7536
7537     int HiIdx = (Offset + 1) * EltBits;
7538     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7539                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7540                                          DAG.getConstant(EltBits, DL, MVT::i8),
7541                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7542     return DAG.getNode(ISD::BITCAST, DL, VT,
7543                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7544   }
7545
7546   // If this would require more than 2 unpack instructions to expand, use
7547   // pshufb when available. We can only use more than 2 unpack instructions
7548   // when zero extending i8 elements which also makes it easier to use pshufb.
7549   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7550     assert(NumElements == 16 && "Unexpected byte vector width!");
7551     SDValue PSHUFBMask[16];
7552     for (int i = 0; i < 16; ++i) {
7553       int Idx = Offset + (i / Scale);
7554       PSHUFBMask[i] = DAG.getConstant(
7555           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7556     }
7557     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7558     return DAG.getBitcast(VT,
7559                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7560                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7561                                                   MVT::v16i8, PSHUFBMask)));
7562   }
7563
7564   // If we are extending from an offset, ensure we start on a boundary that
7565   // we can unpack from.
7566   int AlignToUnpack = Offset % (NumElements / Scale);
7567   if (AlignToUnpack) {
7568     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7569     for (int i = AlignToUnpack; i < NumElements; ++i)
7570       ShMask[i - AlignToUnpack] = i;
7571     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7572     Offset -= AlignToUnpack;
7573   }
7574
7575   // Otherwise emit a sequence of unpacks.
7576   do {
7577     unsigned UnpackLoHi = X86ISD::UNPCKL;
7578     if (Offset >= (NumElements / 2)) {
7579       UnpackLoHi = X86ISD::UNPCKH;
7580       Offset -= (NumElements / 2);
7581     }
7582
7583     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7584     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7585                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7586     InputV = DAG.getBitcast(InputVT, InputV);
7587     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7588     Scale /= 2;
7589     EltBits *= 2;
7590     NumElements /= 2;
7591   } while (Scale > 1);
7592   return DAG.getBitcast(VT, InputV);
7593 }
7594
7595 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7596 ///
7597 /// This routine will try to do everything in its power to cleverly lower
7598 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7599 /// check for the profitability of this lowering,  it tries to aggressively
7600 /// match this pattern. It will use all of the micro-architectural details it
7601 /// can to emit an efficient lowering. It handles both blends with all-zero
7602 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7603 /// masking out later).
7604 ///
7605 /// The reason we have dedicated lowering for zext-style shuffles is that they
7606 /// are both incredibly common and often quite performance sensitive.
7607 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7608     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7609     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7610   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7611
7612   int Bits = VT.getSizeInBits();
7613   int NumLanes = Bits / 128;
7614   int NumElements = VT.getVectorNumElements();
7615   int NumEltsPerLane = NumElements / NumLanes;
7616   assert(VT.getScalarSizeInBits() <= 32 &&
7617          "Exceeds 32-bit integer zero extension limit");
7618   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7619
7620   // Define a helper function to check a particular ext-scale and lower to it if
7621   // valid.
7622   auto Lower = [&](int Scale) -> SDValue {
7623     SDValue InputV;
7624     bool AnyExt = true;
7625     int Offset = 0;
7626     int Matches = 0;
7627     for (int i = 0; i < NumElements; ++i) {
7628       int M = Mask[i];
7629       if (M == -1)
7630         continue; // Valid anywhere but doesn't tell us anything.
7631       if (i % Scale != 0) {
7632         // Each of the extended elements need to be zeroable.
7633         if (!Zeroable[i])
7634           return SDValue();
7635
7636         // We no longer are in the anyext case.
7637         AnyExt = false;
7638         continue;
7639       }
7640
7641       // Each of the base elements needs to be consecutive indices into the
7642       // same input vector.
7643       SDValue V = M < NumElements ? V1 : V2;
7644       M = M % NumElements;
7645       if (!InputV) {
7646         InputV = V;
7647         Offset = M - (i / Scale);
7648       } else if (InputV != V)
7649         return SDValue(); // Flip-flopping inputs.
7650
7651       // Offset must start in the lowest 128-bit lane or at the start of an
7652       // upper lane.
7653       // FIXME: Is it ever worth allowing a negative base offset?
7654       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7655             (Offset % NumEltsPerLane) == 0))
7656         return SDValue();
7657
7658       // If we are offsetting, all referenced entries must come from the same
7659       // lane.
7660       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7661         return SDValue();
7662
7663       if ((M % NumElements) != (Offset + (i / Scale)))
7664         return SDValue(); // Non-consecutive strided elements.
7665       Matches++;
7666     }
7667
7668     // If we fail to find an input, we have a zero-shuffle which should always
7669     // have already been handled.
7670     // FIXME: Maybe handle this here in case during blending we end up with one?
7671     if (!InputV)
7672       return SDValue();
7673
7674     // If we are offsetting, don't extend if we only match a single input, we
7675     // can always do better by using a basic PSHUF or PUNPCK.
7676     if (Offset != 0 && Matches < 2)
7677       return SDValue();
7678
7679     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7680         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7681   };
7682
7683   // The widest scale possible for extending is to a 64-bit integer.
7684   assert(Bits % 64 == 0 &&
7685          "The number of bits in a vector must be divisible by 64 on x86!");
7686   int NumExtElements = Bits / 64;
7687
7688   // Each iteration, try extending the elements half as much, but into twice as
7689   // many elements.
7690   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7691     assert(NumElements % NumExtElements == 0 &&
7692            "The input vector size must be divisible by the extended size.");
7693     if (SDValue V = Lower(NumElements / NumExtElements))
7694       return V;
7695   }
7696
7697   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7698   if (Bits != 128)
7699     return SDValue();
7700
7701   // Returns one of the source operands if the shuffle can be reduced to a
7702   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7703   auto CanZExtLowHalf = [&]() {
7704     for (int i = NumElements / 2; i != NumElements; ++i)
7705       if (!Zeroable[i])
7706         return SDValue();
7707     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7708       return V1;
7709     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7710       return V2;
7711     return SDValue();
7712   };
7713
7714   if (SDValue V = CanZExtLowHalf()) {
7715     V = DAG.getBitcast(MVT::v2i64, V);
7716     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7717     return DAG.getBitcast(VT, V);
7718   }
7719
7720   // No viable ext lowering found.
7721   return SDValue();
7722 }
7723
7724 /// \brief Try to get a scalar value for a specific element of a vector.
7725 ///
7726 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7727 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7728                                               SelectionDAG &DAG) {
7729   MVT VT = V.getSimpleValueType();
7730   MVT EltVT = VT.getVectorElementType();
7731   while (V.getOpcode() == ISD::BITCAST)
7732     V = V.getOperand(0);
7733   // If the bitcasts shift the element size, we can't extract an equivalent
7734   // element from it.
7735   MVT NewVT = V.getSimpleValueType();
7736   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7737     return SDValue();
7738
7739   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7740       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7741     // Ensure the scalar operand is the same size as the destination.
7742     // FIXME: Add support for scalar truncation where possible.
7743     SDValue S = V.getOperand(Idx);
7744     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7745       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7746   }
7747
7748   return SDValue();
7749 }
7750
7751 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7752 ///
7753 /// This is particularly important because the set of instructions varies
7754 /// significantly based on whether the operand is a load or not.
7755 static bool isShuffleFoldableLoad(SDValue V) {
7756   while (V.getOpcode() == ISD::BITCAST)
7757     V = V.getOperand(0);
7758
7759   return ISD::isNON_EXTLoad(V.getNode());
7760 }
7761
7762 /// \brief Try to lower insertion of a single element into a zero vector.
7763 ///
7764 /// This is a common pattern that we have especially efficient patterns to lower
7765 /// across all subtarget feature sets.
7766 static SDValue lowerVectorShuffleAsElementInsertion(
7767     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7768     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7769   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7770   MVT ExtVT = VT;
7771   MVT EltVT = VT.getVectorElementType();
7772
7773   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7774                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7775                 Mask.begin();
7776   bool IsV1Zeroable = true;
7777   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7778     if (i != V2Index && !Zeroable[i]) {
7779       IsV1Zeroable = false;
7780       break;
7781     }
7782
7783   // Check for a single input from a SCALAR_TO_VECTOR node.
7784   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7785   // all the smarts here sunk into that routine. However, the current
7786   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7787   // vector shuffle lowering is dead.
7788   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7789                                                DAG);
7790   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7791     // We need to zext the scalar if it is smaller than an i32.
7792     V2S = DAG.getBitcast(EltVT, V2S);
7793     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7794       // Using zext to expand a narrow element won't work for non-zero
7795       // insertions.
7796       if (!IsV1Zeroable)
7797         return SDValue();
7798
7799       // Zero-extend directly to i32.
7800       ExtVT = MVT::v4i32;
7801       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7802     }
7803     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7804   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7805              EltVT == MVT::i16) {
7806     // Either not inserting from the low element of the input or the input
7807     // element size is too small to use VZEXT_MOVL to clear the high bits.
7808     return SDValue();
7809   }
7810
7811   if (!IsV1Zeroable) {
7812     // If V1 can't be treated as a zero vector we have fewer options to lower
7813     // this. We can't support integer vectors or non-zero targets cheaply, and
7814     // the V1 elements can't be permuted in any way.
7815     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7816     if (!VT.isFloatingPoint() || V2Index != 0)
7817       return SDValue();
7818     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7819     V1Mask[V2Index] = -1;
7820     if (!isNoopShuffleMask(V1Mask))
7821       return SDValue();
7822     // This is essentially a special case blend operation, but if we have
7823     // general purpose blend operations, they are always faster. Bail and let
7824     // the rest of the lowering handle these as blends.
7825     if (Subtarget->hasSSE41())
7826       return SDValue();
7827
7828     // Otherwise, use MOVSD or MOVSS.
7829     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7830            "Only two types of floating point element types to handle!");
7831     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7832                        ExtVT, V1, V2);
7833   }
7834
7835   // This lowering only works for the low element with floating point vectors.
7836   if (VT.isFloatingPoint() && V2Index != 0)
7837     return SDValue();
7838
7839   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7840   if (ExtVT != VT)
7841     V2 = DAG.getBitcast(VT, V2);
7842
7843   if (V2Index != 0) {
7844     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7845     // the desired position. Otherwise it is more efficient to do a vector
7846     // shift left. We know that we can do a vector shift left because all
7847     // the inputs are zero.
7848     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7849       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7850       V2Shuffle[V2Index] = 0;
7851       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7852     } else {
7853       V2 = DAG.getBitcast(MVT::v2i64, V2);
7854       V2 = DAG.getNode(
7855           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7856           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7857                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7858                               DAG.getDataLayout(), VT)));
7859       V2 = DAG.getBitcast(VT, V2);
7860     }
7861   }
7862   return V2;
7863 }
7864
7865 /// \brief Try to lower broadcast of a single - truncated - integer element,
7866 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
7867 ///
7868 /// This assumes we have AVX2.
7869 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
7870                                                   int BroadcastIdx,
7871                                                   const X86Subtarget *Subtarget,
7872                                                   SelectionDAG &DAG) {
7873   assert(Subtarget->hasAVX2() &&
7874          "We can only lower integer broadcasts with AVX2!");
7875
7876   EVT EltVT = VT.getVectorElementType();
7877   EVT V0VT = V0.getValueType();
7878
7879   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
7880   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
7881
7882   EVT V0EltVT = V0VT.getVectorElementType();
7883   if (!V0EltVT.isInteger())
7884     return SDValue();
7885
7886   const unsigned EltSize = EltVT.getSizeInBits();
7887   const unsigned V0EltSize = V0EltVT.getSizeInBits();
7888
7889   // This is only a truncation if the original element type is larger.
7890   if (V0EltSize <= EltSize)
7891     return SDValue();
7892
7893   assert(((V0EltSize % EltSize) == 0) &&
7894          "Scalar type sizes must all be powers of 2 on x86!");
7895
7896   const unsigned V0Opc = V0.getOpcode();
7897   const unsigned Scale = V0EltSize / EltSize;
7898   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
7899
7900   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
7901       V0Opc != ISD::BUILD_VECTOR)
7902     return SDValue();
7903
7904   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
7905
7906   // If we're extracting non-least-significant bits, shift so we can truncate.
7907   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
7908   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
7909   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
7910   if (const int OffsetIdx = BroadcastIdx % Scale)
7911     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
7912             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
7913
7914   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
7915                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
7916 }
7917
7918 /// \brief Try to lower broadcast of a single element.
7919 ///
7920 /// For convenience, this code also bundles all of the subtarget feature set
7921 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7922 /// a convenient way to factor it out.
7923 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7924                                              ArrayRef<int> Mask,
7925                                              const X86Subtarget *Subtarget,
7926                                              SelectionDAG &DAG) {
7927   if (!Subtarget->hasAVX())
7928     return SDValue();
7929   if (VT.isInteger() && !Subtarget->hasAVX2())
7930     return SDValue();
7931
7932   // Check that the mask is a broadcast.
7933   int BroadcastIdx = -1;
7934   for (int M : Mask)
7935     if (M >= 0 && BroadcastIdx == -1)
7936       BroadcastIdx = M;
7937     else if (M >= 0 && M != BroadcastIdx)
7938       return SDValue();
7939
7940   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7941                                             "a sorted mask where the broadcast "
7942                                             "comes from V1.");
7943
7944   // Go up the chain of (vector) values to find a scalar load that we can
7945   // combine with the broadcast.
7946   for (;;) {
7947     switch (V.getOpcode()) {
7948     case ISD::CONCAT_VECTORS: {
7949       int OperandSize = Mask.size() / V.getNumOperands();
7950       V = V.getOperand(BroadcastIdx / OperandSize);
7951       BroadcastIdx %= OperandSize;
7952       continue;
7953     }
7954
7955     case ISD::INSERT_SUBVECTOR: {
7956       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7957       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7958       if (!ConstantIdx)
7959         break;
7960
7961       int BeginIdx = (int)ConstantIdx->getZExtValue();
7962       int EndIdx =
7963           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
7964       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7965         BroadcastIdx -= BeginIdx;
7966         V = VInner;
7967       } else {
7968         V = VOuter;
7969       }
7970       continue;
7971     }
7972     }
7973     break;
7974   }
7975
7976   // Check if this is a broadcast of a scalar. We special case lowering
7977   // for scalars so that we can more effectively fold with loads.
7978   // First, look through bitcast: if the original value has a larger element
7979   // type than the shuffle, the broadcast element is in essence truncated.
7980   // Make that explicit to ease folding.
7981   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
7982     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
7983             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
7984       return TruncBroadcast;
7985
7986   // Also check the simpler case, where we can directly reuse the scalar.
7987   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7988       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7989     V = V.getOperand(BroadcastIdx);
7990
7991     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7992     // Only AVX2 has register broadcasts.
7993     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7994       return SDValue();
7995   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7996     // We can't broadcast from a vector register without AVX2, and we can only
7997     // broadcast from the zero-element of a vector register.
7998     return SDValue();
7999   }
8000
8001   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8002 }
8003
8004 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8005 // INSERTPS when the V1 elements are already in the correct locations
8006 // because otherwise we can just always use two SHUFPS instructions which
8007 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8008 // perform INSERTPS if a single V1 element is out of place and all V2
8009 // elements are zeroable.
8010 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8011                                             ArrayRef<int> Mask,
8012                                             SelectionDAG &DAG) {
8013   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8014   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8015   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8016   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8017
8018   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8019
8020   unsigned ZMask = 0;
8021   int V1DstIndex = -1;
8022   int V2DstIndex = -1;
8023   bool V1UsedInPlace = false;
8024
8025   for (int i = 0; i < 4; ++i) {
8026     // Synthesize a zero mask from the zeroable elements (includes undefs).
8027     if (Zeroable[i]) {
8028       ZMask |= 1 << i;
8029       continue;
8030     }
8031
8032     // Flag if we use any V1 inputs in place.
8033     if (i == Mask[i]) {
8034       V1UsedInPlace = true;
8035       continue;
8036     }
8037
8038     // We can only insert a single non-zeroable element.
8039     if (V1DstIndex != -1 || V2DstIndex != -1)
8040       return SDValue();
8041
8042     if (Mask[i] < 4) {
8043       // V1 input out of place for insertion.
8044       V1DstIndex = i;
8045     } else {
8046       // V2 input for insertion.
8047       V2DstIndex = i;
8048     }
8049   }
8050
8051   // Don't bother if we have no (non-zeroable) element for insertion.
8052   if (V1DstIndex == -1 && V2DstIndex == -1)
8053     return SDValue();
8054
8055   // Determine element insertion src/dst indices. The src index is from the
8056   // start of the inserted vector, not the start of the concatenated vector.
8057   unsigned V2SrcIndex = 0;
8058   if (V1DstIndex != -1) {
8059     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8060     // and don't use the original V2 at all.
8061     V2SrcIndex = Mask[V1DstIndex];
8062     V2DstIndex = V1DstIndex;
8063     V2 = V1;
8064   } else {
8065     V2SrcIndex = Mask[V2DstIndex] - 4;
8066   }
8067
8068   // If no V1 inputs are used in place, then the result is created only from
8069   // the zero mask and the V2 insertion - so remove V1 dependency.
8070   if (!V1UsedInPlace)
8071     V1 = DAG.getUNDEF(MVT::v4f32);
8072
8073   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8074   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8075
8076   // Insert the V2 element into the desired position.
8077   SDLoc DL(Op);
8078   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8079                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8080 }
8081
8082 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8083 /// UNPCK instruction.
8084 ///
8085 /// This specifically targets cases where we end up with alternating between
8086 /// the two inputs, and so can permute them into something that feeds a single
8087 /// UNPCK instruction. Note that this routine only targets integer vectors
8088 /// because for floating point vectors we have a generalized SHUFPS lowering
8089 /// strategy that handles everything that doesn't *exactly* match an unpack,
8090 /// making this clever lowering unnecessary.
8091 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8092                                                     SDValue V1, SDValue V2,
8093                                                     ArrayRef<int> Mask,
8094                                                     SelectionDAG &DAG) {
8095   assert(!VT.isFloatingPoint() &&
8096          "This routine only supports integer vectors.");
8097   assert(!isSingleInputShuffleMask(Mask) &&
8098          "This routine should only be used when blending two inputs.");
8099   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8100
8101   int Size = Mask.size();
8102
8103   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8104     return M >= 0 && M % Size < Size / 2;
8105   });
8106   int NumHiInputs = std::count_if(
8107       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8108
8109   bool UnpackLo = NumLoInputs >= NumHiInputs;
8110
8111   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8112     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8113     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8114
8115     for (int i = 0; i < Size; ++i) {
8116       if (Mask[i] < 0)
8117         continue;
8118
8119       // Each element of the unpack contains Scale elements from this mask.
8120       int UnpackIdx = i / Scale;
8121
8122       // We only handle the case where V1 feeds the first slots of the unpack.
8123       // We rely on canonicalization to ensure this is the case.
8124       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8125         return SDValue();
8126
8127       // Setup the mask for this input. The indexing is tricky as we have to
8128       // handle the unpack stride.
8129       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8130       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8131           Mask[i] % Size;
8132     }
8133
8134     // If we will have to shuffle both inputs to use the unpack, check whether
8135     // we can just unpack first and shuffle the result. If so, skip this unpack.
8136     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8137         !isNoopShuffleMask(V2Mask))
8138       return SDValue();
8139
8140     // Shuffle the inputs into place.
8141     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8142     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8143
8144     // Cast the inputs to the type we will use to unpack them.
8145     V1 = DAG.getBitcast(UnpackVT, V1);
8146     V2 = DAG.getBitcast(UnpackVT, V2);
8147
8148     // Unpack the inputs and cast the result back to the desired type.
8149     return DAG.getBitcast(
8150         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8151                         UnpackVT, V1, V2));
8152   };
8153
8154   // We try each unpack from the largest to the smallest to try and find one
8155   // that fits this mask.
8156   int OrigNumElements = VT.getVectorNumElements();
8157   int OrigScalarSize = VT.getScalarSizeInBits();
8158   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8159     int Scale = ScalarSize / OrigScalarSize;
8160     int NumElements = OrigNumElements / Scale;
8161     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8162     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8163       return Unpack;
8164   }
8165
8166   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8167   // initial unpack.
8168   if (NumLoInputs == 0 || NumHiInputs == 0) {
8169     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8170            "We have to have *some* inputs!");
8171     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8172
8173     // FIXME: We could consider the total complexity of the permute of each
8174     // possible unpacking. Or at the least we should consider how many
8175     // half-crossings are created.
8176     // FIXME: We could consider commuting the unpacks.
8177
8178     SmallVector<int, 32> PermMask;
8179     PermMask.assign(Size, -1);
8180     for (int i = 0; i < Size; ++i) {
8181       if (Mask[i] < 0)
8182         continue;
8183
8184       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8185
8186       PermMask[i] =
8187           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8188     }
8189     return DAG.getVectorShuffle(
8190         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8191                             DL, VT, V1, V2),
8192         DAG.getUNDEF(VT), PermMask);
8193   }
8194
8195   return SDValue();
8196 }
8197
8198 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8199 ///
8200 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8201 /// support for floating point shuffles but not integer shuffles. These
8202 /// instructions will incur a domain crossing penalty on some chips though so
8203 /// it is better to avoid lowering through this for integer vectors where
8204 /// possible.
8205 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8206                                        const X86Subtarget *Subtarget,
8207                                        SelectionDAG &DAG) {
8208   SDLoc DL(Op);
8209   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8210   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8211   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8212   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8213   ArrayRef<int> Mask = SVOp->getMask();
8214   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8215
8216   if (isSingleInputShuffleMask(Mask)) {
8217     // Use low duplicate instructions for masks that match their pattern.
8218     if (Subtarget->hasSSE3())
8219       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8220         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8221
8222     // Straight shuffle of a single input vector. Simulate this by using the
8223     // single input as both of the "inputs" to this instruction..
8224     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8225
8226     if (Subtarget->hasAVX()) {
8227       // If we have AVX, we can use VPERMILPS which will allow folding a load
8228       // into the shuffle.
8229       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8230                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8231     }
8232
8233     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8234                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8235   }
8236   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8237   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8238
8239   // If we have a single input, insert that into V1 if we can do so cheaply.
8240   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8241     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8242             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8243       return Insertion;
8244     // Try inverting the insertion since for v2 masks it is easy to do and we
8245     // can't reliably sort the mask one way or the other.
8246     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8247                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8248     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8249             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8250       return Insertion;
8251   }
8252
8253   // Try to use one of the special instruction patterns to handle two common
8254   // blend patterns if a zero-blend above didn't work.
8255   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8256       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8257     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8258       // We can either use a special instruction to load over the low double or
8259       // to move just the low double.
8260       return DAG.getNode(
8261           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8262           DL, MVT::v2f64, V2,
8263           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8264
8265   if (Subtarget->hasSSE41())
8266     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8267                                                   Subtarget, DAG))
8268       return Blend;
8269
8270   // Use dedicated unpack instructions for masks that match their pattern.
8271   if (SDValue V =
8272           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8273     return V;
8274
8275   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8276   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8277                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8278 }
8279
8280 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8281 ///
8282 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8283 /// the integer unit to minimize domain crossing penalties. However, for blends
8284 /// it falls back to the floating point shuffle operation with appropriate bit
8285 /// casting.
8286 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8287                                        const X86Subtarget *Subtarget,
8288                                        SelectionDAG &DAG) {
8289   SDLoc DL(Op);
8290   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8291   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8292   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8293   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8294   ArrayRef<int> Mask = SVOp->getMask();
8295   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8296
8297   if (isSingleInputShuffleMask(Mask)) {
8298     // Check for being able to broadcast a single element.
8299     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8300                                                           Mask, Subtarget, DAG))
8301       return Broadcast;
8302
8303     // Straight shuffle of a single input vector. For everything from SSE2
8304     // onward this has a single fast instruction with no scary immediates.
8305     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8306     V1 = DAG.getBitcast(MVT::v4i32, V1);
8307     int WidenedMask[4] = {
8308         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8309         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8310     return DAG.getBitcast(
8311         MVT::v2i64,
8312         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8313                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8314   }
8315   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8316   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8317   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8318   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8319
8320   // If we have a blend of two PACKUS operations an the blend aligns with the
8321   // low and half halves, we can just merge the PACKUS operations. This is
8322   // particularly important as it lets us merge shuffles that this routine itself
8323   // creates.
8324   auto GetPackNode = [](SDValue V) {
8325     while (V.getOpcode() == ISD::BITCAST)
8326       V = V.getOperand(0);
8327
8328     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8329   };
8330   if (SDValue V1Pack = GetPackNode(V1))
8331     if (SDValue V2Pack = GetPackNode(V2))
8332       return DAG.getBitcast(MVT::v2i64,
8333                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8334                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8335                                                      : V1Pack.getOperand(1),
8336                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8337                                                      : V2Pack.getOperand(1)));
8338
8339   // Try to use shift instructions.
8340   if (SDValue Shift =
8341           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8342     return Shift;
8343
8344   // When loading a scalar and then shuffling it into a vector we can often do
8345   // the insertion cheaply.
8346   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8347           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8348     return Insertion;
8349   // Try inverting the insertion since for v2 masks it is easy to do and we
8350   // can't reliably sort the mask one way or the other.
8351   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8352   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8353           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8354     return Insertion;
8355
8356   // We have different paths for blend lowering, but they all must use the
8357   // *exact* same predicate.
8358   bool IsBlendSupported = Subtarget->hasSSE41();
8359   if (IsBlendSupported)
8360     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8361                                                   Subtarget, DAG))
8362       return Blend;
8363
8364   // Use dedicated unpack instructions for masks that match their pattern.
8365   if (SDValue V =
8366           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8367     return V;
8368
8369   // Try to use byte rotation instructions.
8370   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8371   if (Subtarget->hasSSSE3())
8372     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8373             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8374       return Rotate;
8375
8376   // If we have direct support for blends, we should lower by decomposing into
8377   // a permute. That will be faster than the domain cross.
8378   if (IsBlendSupported)
8379     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8380                                                       Mask, DAG);
8381
8382   // We implement this with SHUFPD which is pretty lame because it will likely
8383   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8384   // However, all the alternatives are still more cycles and newer chips don't
8385   // have this problem. It would be really nice if x86 had better shuffles here.
8386   V1 = DAG.getBitcast(MVT::v2f64, V1);
8387   V2 = DAG.getBitcast(MVT::v2f64, V2);
8388   return DAG.getBitcast(MVT::v2i64,
8389                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8390 }
8391
8392 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8393 ///
8394 /// This is used to disable more specialized lowerings when the shufps lowering
8395 /// will happen to be efficient.
8396 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8397   // This routine only handles 128-bit shufps.
8398   assert(Mask.size() == 4 && "Unsupported mask size!");
8399
8400   // To lower with a single SHUFPS we need to have the low half and high half
8401   // each requiring a single input.
8402   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8403     return false;
8404   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8405     return false;
8406
8407   return true;
8408 }
8409
8410 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8411 ///
8412 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8413 /// It makes no assumptions about whether this is the *best* lowering, it simply
8414 /// uses it.
8415 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8416                                             ArrayRef<int> Mask, SDValue V1,
8417                                             SDValue V2, SelectionDAG &DAG) {
8418   SDValue LowV = V1, HighV = V2;
8419   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8420
8421   int NumV2Elements =
8422       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8423
8424   if (NumV2Elements == 1) {
8425     int V2Index =
8426         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8427         Mask.begin();
8428
8429     // Compute the index adjacent to V2Index and in the same half by toggling
8430     // the low bit.
8431     int V2AdjIndex = V2Index ^ 1;
8432
8433     if (Mask[V2AdjIndex] == -1) {
8434       // Handles all the cases where we have a single V2 element and an undef.
8435       // This will only ever happen in the high lanes because we commute the
8436       // vector otherwise.
8437       if (V2Index < 2)
8438         std::swap(LowV, HighV);
8439       NewMask[V2Index] -= 4;
8440     } else {
8441       // Handle the case where the V2 element ends up adjacent to a V1 element.
8442       // To make this work, blend them together as the first step.
8443       int V1Index = V2AdjIndex;
8444       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8445       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8446                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8447
8448       // Now proceed to reconstruct the final blend as we have the necessary
8449       // high or low half formed.
8450       if (V2Index < 2) {
8451         LowV = V2;
8452         HighV = V1;
8453       } else {
8454         HighV = V2;
8455       }
8456       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8457       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8458     }
8459   } else if (NumV2Elements == 2) {
8460     if (Mask[0] < 4 && Mask[1] < 4) {
8461       // Handle the easy case where we have V1 in the low lanes and V2 in the
8462       // high lanes.
8463       NewMask[2] -= 4;
8464       NewMask[3] -= 4;
8465     } else if (Mask[2] < 4 && Mask[3] < 4) {
8466       // We also handle the reversed case because this utility may get called
8467       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8468       // arrange things in the right direction.
8469       NewMask[0] -= 4;
8470       NewMask[1] -= 4;
8471       HighV = V1;
8472       LowV = V2;
8473     } else {
8474       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8475       // trying to place elements directly, just blend them and set up the final
8476       // shuffle to place them.
8477
8478       // The first two blend mask elements are for V1, the second two are for
8479       // V2.
8480       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8481                           Mask[2] < 4 ? Mask[2] : Mask[3],
8482                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8483                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8484       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8485                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8486
8487       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8488       // a blend.
8489       LowV = HighV = V1;
8490       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8491       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8492       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8493       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8494     }
8495   }
8496   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8497                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8498 }
8499
8500 /// \brief Lower 4-lane 32-bit floating point shuffles.
8501 ///
8502 /// Uses instructions exclusively from the floating point unit to minimize
8503 /// domain crossing penalties, as these are sufficient to implement all v4f32
8504 /// shuffles.
8505 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8506                                        const X86Subtarget *Subtarget,
8507                                        SelectionDAG &DAG) {
8508   SDLoc DL(Op);
8509   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8510   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8511   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8512   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8513   ArrayRef<int> Mask = SVOp->getMask();
8514   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8515
8516   int NumV2Elements =
8517       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8518
8519   if (NumV2Elements == 0) {
8520     // Check for being able to broadcast a single element.
8521     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8522                                                           Mask, Subtarget, DAG))
8523       return Broadcast;
8524
8525     // Use even/odd duplicate instructions for masks that match their pattern.
8526     if (Subtarget->hasSSE3()) {
8527       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8528         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8529       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8530         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8531     }
8532
8533     if (Subtarget->hasAVX()) {
8534       // If we have AVX, we can use VPERMILPS which will allow folding a load
8535       // into the shuffle.
8536       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8537                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8538     }
8539
8540     // Otherwise, use a straight shuffle of a single input vector. We pass the
8541     // input vector to both operands to simulate this with a SHUFPS.
8542     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8543                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8544   }
8545
8546   // There are special ways we can lower some single-element blends. However, we
8547   // have custom ways we can lower more complex single-element blends below that
8548   // we defer to if both this and BLENDPS fail to match, so restrict this to
8549   // when the V2 input is targeting element 0 of the mask -- that is the fast
8550   // case here.
8551   if (NumV2Elements == 1 && Mask[0] >= 4)
8552     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8553                                                          Mask, Subtarget, DAG))
8554       return V;
8555
8556   if (Subtarget->hasSSE41()) {
8557     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8558                                                   Subtarget, DAG))
8559       return Blend;
8560
8561     // Use INSERTPS if we can complete the shuffle efficiently.
8562     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8563       return V;
8564
8565     if (!isSingleSHUFPSMask(Mask))
8566       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8567               DL, MVT::v4f32, V1, V2, Mask, DAG))
8568         return BlendPerm;
8569   }
8570
8571   // Use dedicated unpack instructions for masks that match their pattern.
8572   if (SDValue V =
8573           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8574     return V;
8575
8576   // Otherwise fall back to a SHUFPS lowering strategy.
8577   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8578 }
8579
8580 /// \brief Lower 4-lane i32 vector shuffles.
8581 ///
8582 /// We try to handle these with integer-domain shuffles where we can, but for
8583 /// blends we use the floating point domain blend instructions.
8584 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8585                                        const X86Subtarget *Subtarget,
8586                                        SelectionDAG &DAG) {
8587   SDLoc DL(Op);
8588   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8589   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8590   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8591   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8592   ArrayRef<int> Mask = SVOp->getMask();
8593   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8594
8595   // Whenever we can lower this as a zext, that instruction is strictly faster
8596   // than any alternative. It also allows us to fold memory operands into the
8597   // shuffle in many cases.
8598   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8599                                                          Mask, Subtarget, DAG))
8600     return ZExt;
8601
8602   int NumV2Elements =
8603       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8604
8605   if (NumV2Elements == 0) {
8606     // Check for being able to broadcast a single element.
8607     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8608                                                           Mask, Subtarget, DAG))
8609       return Broadcast;
8610
8611     // Straight shuffle of a single input vector. For everything from SSE2
8612     // onward this has a single fast instruction with no scary immediates.
8613     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8614     // but we aren't actually going to use the UNPCK instruction because doing
8615     // so prevents folding a load into this instruction or making a copy.
8616     const int UnpackLoMask[] = {0, 0, 1, 1};
8617     const int UnpackHiMask[] = {2, 2, 3, 3};
8618     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8619       Mask = UnpackLoMask;
8620     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8621       Mask = UnpackHiMask;
8622
8623     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8624                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8625   }
8626
8627   // Try to use shift instructions.
8628   if (SDValue Shift =
8629           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8630     return Shift;
8631
8632   // There are special ways we can lower some single-element blends.
8633   if (NumV2Elements == 1)
8634     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8635                                                          Mask, Subtarget, DAG))
8636       return V;
8637
8638   // We have different paths for blend lowering, but they all must use the
8639   // *exact* same predicate.
8640   bool IsBlendSupported = Subtarget->hasSSE41();
8641   if (IsBlendSupported)
8642     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8643                                                   Subtarget, DAG))
8644       return Blend;
8645
8646   if (SDValue Masked =
8647           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8648     return Masked;
8649
8650   // Use dedicated unpack instructions for masks that match their pattern.
8651   if (SDValue V =
8652           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8653     return V;
8654
8655   // Try to use byte rotation instructions.
8656   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8657   if (Subtarget->hasSSSE3())
8658     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8659             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8660       return Rotate;
8661
8662   // If we have direct support for blends, we should lower by decomposing into
8663   // a permute. That will be faster than the domain cross.
8664   if (IsBlendSupported)
8665     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8666                                                       Mask, DAG);
8667
8668   // Try to lower by permuting the inputs into an unpack instruction.
8669   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8670                                                             V2, Mask, DAG))
8671     return Unpack;
8672
8673   // We implement this with SHUFPS because it can blend from two vectors.
8674   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8675   // up the inputs, bypassing domain shift penalties that we would encur if we
8676   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8677   // relevant.
8678   return DAG.getBitcast(
8679       MVT::v4i32,
8680       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8681                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8682 }
8683
8684 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8685 /// shuffle lowering, and the most complex part.
8686 ///
8687 /// The lowering strategy is to try to form pairs of input lanes which are
8688 /// targeted at the same half of the final vector, and then use a dword shuffle
8689 /// to place them onto the right half, and finally unpack the paired lanes into
8690 /// their final position.
8691 ///
8692 /// The exact breakdown of how to form these dword pairs and align them on the
8693 /// correct sides is really tricky. See the comments within the function for
8694 /// more of the details.
8695 ///
8696 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8697 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8698 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8699 /// vector, form the analogous 128-bit 8-element Mask.
8700 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8701     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8702     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8703   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8704   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8705
8706   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8707   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8708   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8709
8710   SmallVector<int, 4> LoInputs;
8711   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8712                [](int M) { return M >= 0; });
8713   std::sort(LoInputs.begin(), LoInputs.end());
8714   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8715   SmallVector<int, 4> HiInputs;
8716   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8717                [](int M) { return M >= 0; });
8718   std::sort(HiInputs.begin(), HiInputs.end());
8719   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8720   int NumLToL =
8721       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8722   int NumHToL = LoInputs.size() - NumLToL;
8723   int NumLToH =
8724       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8725   int NumHToH = HiInputs.size() - NumLToH;
8726   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8727   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8728   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8729   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8730
8731   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8732   // such inputs we can swap two of the dwords across the half mark and end up
8733   // with <=2 inputs to each half in each half. Once there, we can fall through
8734   // to the generic code below. For example:
8735   //
8736   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8737   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8738   //
8739   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8740   // and an existing 2-into-2 on the other half. In this case we may have to
8741   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8742   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8743   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8744   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8745   // half than the one we target for fixing) will be fixed when we re-enter this
8746   // path. We will also combine away any sequence of PSHUFD instructions that
8747   // result into a single instruction. Here is an example of the tricky case:
8748   //
8749   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8750   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8751   //
8752   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8753   //
8754   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8755   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8756   //
8757   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8758   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8759   //
8760   // The result is fine to be handled by the generic logic.
8761   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8762                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8763                           int AOffset, int BOffset) {
8764     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8765            "Must call this with A having 3 or 1 inputs from the A half.");
8766     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8767            "Must call this with B having 1 or 3 inputs from the B half.");
8768     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8769            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8770
8771     bool ThreeAInputs = AToAInputs.size() == 3;
8772
8773     // Compute the index of dword with only one word among the three inputs in
8774     // a half by taking the sum of the half with three inputs and subtracting
8775     // the sum of the actual three inputs. The difference is the remaining
8776     // slot.
8777     int ADWord, BDWord;
8778     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8779     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8780     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8781     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8782     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8783     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8784     int TripleNonInputIdx =
8785         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8786     TripleDWord = TripleNonInputIdx / 2;
8787
8788     // We use xor with one to compute the adjacent DWord to whichever one the
8789     // OneInput is in.
8790     OneInputDWord = (OneInput / 2) ^ 1;
8791
8792     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8793     // and BToA inputs. If there is also such a problem with the BToB and AToB
8794     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8795     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8796     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8797     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8798       // Compute how many inputs will be flipped by swapping these DWords. We
8799       // need
8800       // to balance this to ensure we don't form a 3-1 shuffle in the other
8801       // half.
8802       int NumFlippedAToBInputs =
8803           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8804           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8805       int NumFlippedBToBInputs =
8806           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8807           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8808       if ((NumFlippedAToBInputs == 1 &&
8809            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8810           (NumFlippedBToBInputs == 1 &&
8811            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8812         // We choose whether to fix the A half or B half based on whether that
8813         // half has zero flipped inputs. At zero, we may not be able to fix it
8814         // with that half. We also bias towards fixing the B half because that
8815         // will more commonly be the high half, and we have to bias one way.
8816         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8817                                                        ArrayRef<int> Inputs) {
8818           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8819           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8820                                          PinnedIdx ^ 1) != Inputs.end();
8821           // Determine whether the free index is in the flipped dword or the
8822           // unflipped dword based on where the pinned index is. We use this bit
8823           // in an xor to conditionally select the adjacent dword.
8824           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8825           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8826                                              FixFreeIdx) != Inputs.end();
8827           if (IsFixIdxInput == IsFixFreeIdxInput)
8828             FixFreeIdx += 1;
8829           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8830                                         FixFreeIdx) != Inputs.end();
8831           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8832                  "We need to be changing the number of flipped inputs!");
8833           int PSHUFHalfMask[] = {0, 1, 2, 3};
8834           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8835           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8836                           MVT::v8i16, V,
8837                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8838
8839           for (int &M : Mask)
8840             if (M != -1 && M == FixIdx)
8841               M = FixFreeIdx;
8842             else if (M != -1 && M == FixFreeIdx)
8843               M = FixIdx;
8844         };
8845         if (NumFlippedBToBInputs != 0) {
8846           int BPinnedIdx =
8847               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8848           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8849         } else {
8850           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8851           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8852           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8853         }
8854       }
8855     }
8856
8857     int PSHUFDMask[] = {0, 1, 2, 3};
8858     PSHUFDMask[ADWord] = BDWord;
8859     PSHUFDMask[BDWord] = ADWord;
8860     V = DAG.getBitcast(
8861         VT,
8862         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8863                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8864
8865     // Adjust the mask to match the new locations of A and B.
8866     for (int &M : Mask)
8867       if (M != -1 && M/2 == ADWord)
8868         M = 2 * BDWord + M % 2;
8869       else if (M != -1 && M/2 == BDWord)
8870         M = 2 * ADWord + M % 2;
8871
8872     // Recurse back into this routine to re-compute state now that this isn't
8873     // a 3 and 1 problem.
8874     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8875                                                      DAG);
8876   };
8877   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8878     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8879   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8880     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8881
8882   // At this point there are at most two inputs to the low and high halves from
8883   // each half. That means the inputs can always be grouped into dwords and
8884   // those dwords can then be moved to the correct half with a dword shuffle.
8885   // We use at most one low and one high word shuffle to collect these paired
8886   // inputs into dwords, and finally a dword shuffle to place them.
8887   int PSHUFLMask[4] = {-1, -1, -1, -1};
8888   int PSHUFHMask[4] = {-1, -1, -1, -1};
8889   int PSHUFDMask[4] = {-1, -1, -1, -1};
8890
8891   // First fix the masks for all the inputs that are staying in their
8892   // original halves. This will then dictate the targets of the cross-half
8893   // shuffles.
8894   auto fixInPlaceInputs =
8895       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8896                     MutableArrayRef<int> SourceHalfMask,
8897                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8898     if (InPlaceInputs.empty())
8899       return;
8900     if (InPlaceInputs.size() == 1) {
8901       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8902           InPlaceInputs[0] - HalfOffset;
8903       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8904       return;
8905     }
8906     if (IncomingInputs.empty()) {
8907       // Just fix all of the in place inputs.
8908       for (int Input : InPlaceInputs) {
8909         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8910         PSHUFDMask[Input / 2] = Input / 2;
8911       }
8912       return;
8913     }
8914
8915     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8916     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8917         InPlaceInputs[0] - HalfOffset;
8918     // Put the second input next to the first so that they are packed into
8919     // a dword. We find the adjacent index by toggling the low bit.
8920     int AdjIndex = InPlaceInputs[0] ^ 1;
8921     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8922     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8923     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8924   };
8925   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8926   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8927
8928   // Now gather the cross-half inputs and place them into a free dword of
8929   // their target half.
8930   // FIXME: This operation could almost certainly be simplified dramatically to
8931   // look more like the 3-1 fixing operation.
8932   auto moveInputsToRightHalf = [&PSHUFDMask](
8933       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8934       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8935       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8936       int DestOffset) {
8937     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8938       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8939     };
8940     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8941                                                int Word) {
8942       int LowWord = Word & ~1;
8943       int HighWord = Word | 1;
8944       return isWordClobbered(SourceHalfMask, LowWord) ||
8945              isWordClobbered(SourceHalfMask, HighWord);
8946     };
8947
8948     if (IncomingInputs.empty())
8949       return;
8950
8951     if (ExistingInputs.empty()) {
8952       // Map any dwords with inputs from them into the right half.
8953       for (int Input : IncomingInputs) {
8954         // If the source half mask maps over the inputs, turn those into
8955         // swaps and use the swapped lane.
8956         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8957           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8958             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8959                 Input - SourceOffset;
8960             // We have to swap the uses in our half mask in one sweep.
8961             for (int &M : HalfMask)
8962               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8963                 M = Input;
8964               else if (M == Input)
8965                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8966           } else {
8967             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8968                        Input - SourceOffset &&
8969                    "Previous placement doesn't match!");
8970           }
8971           // Note that this correctly re-maps both when we do a swap and when
8972           // we observe the other side of the swap above. We rely on that to
8973           // avoid swapping the members of the input list directly.
8974           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8975         }
8976
8977         // Map the input's dword into the correct half.
8978         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8979           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8980         else
8981           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8982                      Input / 2 &&
8983                  "Previous placement doesn't match!");
8984       }
8985
8986       // And just directly shift any other-half mask elements to be same-half
8987       // as we will have mirrored the dword containing the element into the
8988       // same position within that half.
8989       for (int &M : HalfMask)
8990         if (M >= SourceOffset && M < SourceOffset + 4) {
8991           M = M - SourceOffset + DestOffset;
8992           assert(M >= 0 && "This should never wrap below zero!");
8993         }
8994       return;
8995     }
8996
8997     // Ensure we have the input in a viable dword of its current half. This
8998     // is particularly tricky because the original position may be clobbered
8999     // by inputs being moved and *staying* in that half.
9000     if (IncomingInputs.size() == 1) {
9001       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9002         int InputFixed = std::find(std::begin(SourceHalfMask),
9003                                    std::end(SourceHalfMask), -1) -
9004                          std::begin(SourceHalfMask) + SourceOffset;
9005         SourceHalfMask[InputFixed - SourceOffset] =
9006             IncomingInputs[0] - SourceOffset;
9007         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9008                      InputFixed);
9009         IncomingInputs[0] = InputFixed;
9010       }
9011     } else if (IncomingInputs.size() == 2) {
9012       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9013           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9014         // We have two non-adjacent or clobbered inputs we need to extract from
9015         // the source half. To do this, we need to map them into some adjacent
9016         // dword slot in the source mask.
9017         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9018                               IncomingInputs[1] - SourceOffset};
9019
9020         // If there is a free slot in the source half mask adjacent to one of
9021         // the inputs, place the other input in it. We use (Index XOR 1) to
9022         // compute an adjacent index.
9023         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9024             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9025           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9026           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9027           InputsFixed[1] = InputsFixed[0] ^ 1;
9028         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9029                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9030           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9031           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9032           InputsFixed[0] = InputsFixed[1] ^ 1;
9033         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9034                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9035           // The two inputs are in the same DWord but it is clobbered and the
9036           // adjacent DWord isn't used at all. Move both inputs to the free
9037           // slot.
9038           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9039           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9040           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9041           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9042         } else {
9043           // The only way we hit this point is if there is no clobbering
9044           // (because there are no off-half inputs to this half) and there is no
9045           // free slot adjacent to one of the inputs. In this case, we have to
9046           // swap an input with a non-input.
9047           for (int i = 0; i < 4; ++i)
9048             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9049                    "We can't handle any clobbers here!");
9050           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9051                  "Cannot have adjacent inputs here!");
9052
9053           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9054           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9055
9056           // We also have to update the final source mask in this case because
9057           // it may need to undo the above swap.
9058           for (int &M : FinalSourceHalfMask)
9059             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9060               M = InputsFixed[1] + SourceOffset;
9061             else if (M == InputsFixed[1] + SourceOffset)
9062               M = (InputsFixed[0] ^ 1) + SourceOffset;
9063
9064           InputsFixed[1] = InputsFixed[0] ^ 1;
9065         }
9066
9067         // Point everything at the fixed inputs.
9068         for (int &M : HalfMask)
9069           if (M == IncomingInputs[0])
9070             M = InputsFixed[0] + SourceOffset;
9071           else if (M == IncomingInputs[1])
9072             M = InputsFixed[1] + SourceOffset;
9073
9074         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9075         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9076       }
9077     } else {
9078       llvm_unreachable("Unhandled input size!");
9079     }
9080
9081     // Now hoist the DWord down to the right half.
9082     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9083     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9084     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9085     for (int &M : HalfMask)
9086       for (int Input : IncomingInputs)
9087         if (M == Input)
9088           M = FreeDWord * 2 + Input % 2;
9089   };
9090   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9091                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9092   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9093                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9094
9095   // Now enact all the shuffles we've computed to move the inputs into their
9096   // target half.
9097   if (!isNoopShuffleMask(PSHUFLMask))
9098     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9099                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9100   if (!isNoopShuffleMask(PSHUFHMask))
9101     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9102                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9103   if (!isNoopShuffleMask(PSHUFDMask))
9104     V = DAG.getBitcast(
9105         VT,
9106         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9107                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9108
9109   // At this point, each half should contain all its inputs, and we can then
9110   // just shuffle them into their final position.
9111   assert(std::count_if(LoMask.begin(), LoMask.end(),
9112                        [](int M) { return M >= 4; }) == 0 &&
9113          "Failed to lift all the high half inputs to the low mask!");
9114   assert(std::count_if(HiMask.begin(), HiMask.end(),
9115                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9116          "Failed to lift all the low half inputs to the high mask!");
9117
9118   // Do a half shuffle for the low mask.
9119   if (!isNoopShuffleMask(LoMask))
9120     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9121                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9122
9123   // Do a half shuffle with the high mask after shifting its values down.
9124   for (int &M : HiMask)
9125     if (M >= 0)
9126       M -= 4;
9127   if (!isNoopShuffleMask(HiMask))
9128     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9129                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9130
9131   return V;
9132 }
9133
9134 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9135 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9136                                           SDValue V2, ArrayRef<int> Mask,
9137                                           SelectionDAG &DAG, bool &V1InUse,
9138                                           bool &V2InUse) {
9139   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9140   SDValue V1Mask[16];
9141   SDValue V2Mask[16];
9142   V1InUse = false;
9143   V2InUse = false;
9144
9145   int Size = Mask.size();
9146   int Scale = 16 / Size;
9147   for (int i = 0; i < 16; ++i) {
9148     if (Mask[i / Scale] == -1) {
9149       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9150     } else {
9151       const int ZeroMask = 0x80;
9152       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9153                                           : ZeroMask;
9154       int V2Idx = Mask[i / Scale] < Size
9155                       ? ZeroMask
9156                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9157       if (Zeroable[i / Scale])
9158         V1Idx = V2Idx = ZeroMask;
9159       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9160       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9161       V1InUse |= (ZeroMask != V1Idx);
9162       V2InUse |= (ZeroMask != V2Idx);
9163     }
9164   }
9165
9166   if (V1InUse)
9167     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9168                      DAG.getBitcast(MVT::v16i8, V1),
9169                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9170   if (V2InUse)
9171     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9172                      DAG.getBitcast(MVT::v16i8, V2),
9173                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9174
9175   // If we need shuffled inputs from both, blend the two.
9176   SDValue V;
9177   if (V1InUse && V2InUse)
9178     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9179   else
9180     V = V1InUse ? V1 : V2;
9181
9182   // Cast the result back to the correct type.
9183   return DAG.getBitcast(VT, V);
9184 }
9185
9186 /// \brief Generic lowering of 8-lane i16 shuffles.
9187 ///
9188 /// This handles both single-input shuffles and combined shuffle/blends with
9189 /// two inputs. The single input shuffles are immediately delegated to
9190 /// a dedicated lowering routine.
9191 ///
9192 /// The blends are lowered in one of three fundamental ways. If there are few
9193 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9194 /// of the input is significantly cheaper when lowered as an interleaving of
9195 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9196 /// halves of the inputs separately (making them have relatively few inputs)
9197 /// and then concatenate them.
9198 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9199                                        const X86Subtarget *Subtarget,
9200                                        SelectionDAG &DAG) {
9201   SDLoc DL(Op);
9202   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9203   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9204   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9205   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9206   ArrayRef<int> OrigMask = SVOp->getMask();
9207   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9208                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9209   MutableArrayRef<int> Mask(MaskStorage);
9210
9211   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9212
9213   // Whenever we can lower this as a zext, that instruction is strictly faster
9214   // than any alternative.
9215   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9216           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9217     return ZExt;
9218
9219   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9220   (void)isV1;
9221   auto isV2 = [](int M) { return M >= 8; };
9222
9223   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9224
9225   if (NumV2Inputs == 0) {
9226     // Check for being able to broadcast a single element.
9227     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9228                                                           Mask, Subtarget, DAG))
9229       return Broadcast;
9230
9231     // Try to use shift instructions.
9232     if (SDValue Shift =
9233             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9234       return Shift;
9235
9236     // Use dedicated unpack instructions for masks that match their pattern.
9237     if (SDValue V =
9238             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9239       return V;
9240
9241     // Try to use byte rotation instructions.
9242     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9243                                                         Mask, Subtarget, DAG))
9244       return Rotate;
9245
9246     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9247                                                      Subtarget, DAG);
9248   }
9249
9250   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9251          "All single-input shuffles should be canonicalized to be V1-input "
9252          "shuffles.");
9253
9254   // Try to use shift instructions.
9255   if (SDValue Shift =
9256           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9257     return Shift;
9258
9259   // See if we can use SSE4A Extraction / Insertion.
9260   if (Subtarget->hasSSE4A())
9261     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9262       return V;
9263
9264   // There are special ways we can lower some single-element blends.
9265   if (NumV2Inputs == 1)
9266     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9267                                                          Mask, Subtarget, DAG))
9268       return V;
9269
9270   // We have different paths for blend lowering, but they all must use the
9271   // *exact* same predicate.
9272   bool IsBlendSupported = Subtarget->hasSSE41();
9273   if (IsBlendSupported)
9274     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9275                                                   Subtarget, DAG))
9276       return Blend;
9277
9278   if (SDValue Masked =
9279           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9280     return Masked;
9281
9282   // Use dedicated unpack instructions for masks that match their pattern.
9283   if (SDValue V =
9284           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9285     return V;
9286
9287   // Try to use byte rotation instructions.
9288   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9289           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9290     return Rotate;
9291
9292   if (SDValue BitBlend =
9293           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9294     return BitBlend;
9295
9296   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9297                                                             V2, Mask, DAG))
9298     return Unpack;
9299
9300   // If we can't directly blend but can use PSHUFB, that will be better as it
9301   // can both shuffle and set up the inefficient blend.
9302   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9303     bool V1InUse, V2InUse;
9304     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9305                                       V1InUse, V2InUse);
9306   }
9307
9308   // We can always bit-blend if we have to so the fallback strategy is to
9309   // decompose into single-input permutes and blends.
9310   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9311                                                       Mask, DAG);
9312 }
9313
9314 /// \brief Check whether a compaction lowering can be done by dropping even
9315 /// elements and compute how many times even elements must be dropped.
9316 ///
9317 /// This handles shuffles which take every Nth element where N is a power of
9318 /// two. Example shuffle masks:
9319 ///
9320 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9321 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9322 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9323 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9324 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9325 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9326 ///
9327 /// Any of these lanes can of course be undef.
9328 ///
9329 /// This routine only supports N <= 3.
9330 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9331 /// for larger N.
9332 ///
9333 /// \returns N above, or the number of times even elements must be dropped if
9334 /// there is such a number. Otherwise returns zero.
9335 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9336   // Figure out whether we're looping over two inputs or just one.
9337   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9338
9339   // The modulus for the shuffle vector entries is based on whether this is
9340   // a single input or not.
9341   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9342   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9343          "We should only be called with masks with a power-of-2 size!");
9344
9345   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9346
9347   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9348   // and 2^3 simultaneously. This is because we may have ambiguity with
9349   // partially undef inputs.
9350   bool ViableForN[3] = {true, true, true};
9351
9352   for (int i = 0, e = Mask.size(); i < e; ++i) {
9353     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9354     // want.
9355     if (Mask[i] == -1)
9356       continue;
9357
9358     bool IsAnyViable = false;
9359     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9360       if (ViableForN[j]) {
9361         uint64_t N = j + 1;
9362
9363         // The shuffle mask must be equal to (i * 2^N) % M.
9364         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9365           IsAnyViable = true;
9366         else
9367           ViableForN[j] = false;
9368       }
9369     // Early exit if we exhaust the possible powers of two.
9370     if (!IsAnyViable)
9371       break;
9372   }
9373
9374   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9375     if (ViableForN[j])
9376       return j + 1;
9377
9378   // Return 0 as there is no viable power of two.
9379   return 0;
9380 }
9381
9382 /// \brief Generic lowering of v16i8 shuffles.
9383 ///
9384 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9385 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9386 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9387 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9388 /// back together.
9389 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9390                                        const X86Subtarget *Subtarget,
9391                                        SelectionDAG &DAG) {
9392   SDLoc DL(Op);
9393   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9394   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9395   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9396   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9397   ArrayRef<int> Mask = SVOp->getMask();
9398   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9399
9400   // Try to use shift instructions.
9401   if (SDValue Shift =
9402           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9403     return Shift;
9404
9405   // Try to use byte rotation instructions.
9406   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9407           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9408     return Rotate;
9409
9410   // Try to use a zext lowering.
9411   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9412           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9413     return ZExt;
9414
9415   // See if we can use SSE4A Extraction / Insertion.
9416   if (Subtarget->hasSSE4A())
9417     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9418       return V;
9419
9420   int NumV2Elements =
9421       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9422
9423   // For single-input shuffles, there are some nicer lowering tricks we can use.
9424   if (NumV2Elements == 0) {
9425     // Check for being able to broadcast a single element.
9426     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9427                                                           Mask, Subtarget, DAG))
9428       return Broadcast;
9429
9430     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9431     // Notably, this handles splat and partial-splat shuffles more efficiently.
9432     // However, it only makes sense if the pre-duplication shuffle simplifies
9433     // things significantly. Currently, this means we need to be able to
9434     // express the pre-duplication shuffle as an i16 shuffle.
9435     //
9436     // FIXME: We should check for other patterns which can be widened into an
9437     // i16 shuffle as well.
9438     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9439       for (int i = 0; i < 16; i += 2)
9440         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9441           return false;
9442
9443       return true;
9444     };
9445     auto tryToWidenViaDuplication = [&]() -> SDValue {
9446       if (!canWidenViaDuplication(Mask))
9447         return SDValue();
9448       SmallVector<int, 4> LoInputs;
9449       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9450                    [](int M) { return M >= 0 && M < 8; });
9451       std::sort(LoInputs.begin(), LoInputs.end());
9452       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9453                      LoInputs.end());
9454       SmallVector<int, 4> HiInputs;
9455       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9456                    [](int M) { return M >= 8; });
9457       std::sort(HiInputs.begin(), HiInputs.end());
9458       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9459                      HiInputs.end());
9460
9461       bool TargetLo = LoInputs.size() >= HiInputs.size();
9462       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9463       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9464
9465       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9466       SmallDenseMap<int, int, 8> LaneMap;
9467       for (int I : InPlaceInputs) {
9468         PreDupI16Shuffle[I/2] = I/2;
9469         LaneMap[I] = I;
9470       }
9471       int j = TargetLo ? 0 : 4, je = j + 4;
9472       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9473         // Check if j is already a shuffle of this input. This happens when
9474         // there are two adjacent bytes after we move the low one.
9475         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9476           // If we haven't yet mapped the input, search for a slot into which
9477           // we can map it.
9478           while (j < je && PreDupI16Shuffle[j] != -1)
9479             ++j;
9480
9481           if (j == je)
9482             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9483             return SDValue();
9484
9485           // Map this input with the i16 shuffle.
9486           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9487         }
9488
9489         // Update the lane map based on the mapping we ended up with.
9490         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9491       }
9492       V1 = DAG.getBitcast(
9493           MVT::v16i8,
9494           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9495                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9496
9497       // Unpack the bytes to form the i16s that will be shuffled into place.
9498       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9499                        MVT::v16i8, V1, V1);
9500
9501       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9502       for (int i = 0; i < 16; ++i)
9503         if (Mask[i] != -1) {
9504           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9505           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9506           if (PostDupI16Shuffle[i / 2] == -1)
9507             PostDupI16Shuffle[i / 2] = MappedMask;
9508           else
9509             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9510                    "Conflicting entrties in the original shuffle!");
9511         }
9512       return DAG.getBitcast(
9513           MVT::v16i8,
9514           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9515                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9516     };
9517     if (SDValue V = tryToWidenViaDuplication())
9518       return V;
9519   }
9520
9521   if (SDValue Masked =
9522           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9523     return Masked;
9524
9525   // Use dedicated unpack instructions for masks that match their pattern.
9526   if (SDValue V =
9527           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9528     return V;
9529
9530   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9531   // with PSHUFB. It is important to do this before we attempt to generate any
9532   // blends but after all of the single-input lowerings. If the single input
9533   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9534   // want to preserve that and we can DAG combine any longer sequences into
9535   // a PSHUFB in the end. But once we start blending from multiple inputs,
9536   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9537   // and there are *very* few patterns that would actually be faster than the
9538   // PSHUFB approach because of its ability to zero lanes.
9539   //
9540   // FIXME: The only exceptions to the above are blends which are exact
9541   // interleavings with direct instructions supporting them. We currently don't
9542   // handle those well here.
9543   if (Subtarget->hasSSSE3()) {
9544     bool V1InUse = false;
9545     bool V2InUse = false;
9546
9547     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9548                                                 DAG, V1InUse, V2InUse);
9549
9550     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9551     // do so. This avoids using them to handle blends-with-zero which is
9552     // important as a single pshufb is significantly faster for that.
9553     if (V1InUse && V2InUse) {
9554       if (Subtarget->hasSSE41())
9555         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9556                                                       Mask, Subtarget, DAG))
9557           return Blend;
9558
9559       // We can use an unpack to do the blending rather than an or in some
9560       // cases. Even though the or may be (very minorly) more efficient, we
9561       // preference this lowering because there are common cases where part of
9562       // the complexity of the shuffles goes away when we do the final blend as
9563       // an unpack.
9564       // FIXME: It might be worth trying to detect if the unpack-feeding
9565       // shuffles will both be pshufb, in which case we shouldn't bother with
9566       // this.
9567       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9568               DL, MVT::v16i8, V1, V2, Mask, DAG))
9569         return Unpack;
9570     }
9571
9572     return PSHUFB;
9573   }
9574
9575   // There are special ways we can lower some single-element blends.
9576   if (NumV2Elements == 1)
9577     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9578                                                          Mask, Subtarget, DAG))
9579       return V;
9580
9581   if (SDValue BitBlend =
9582           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9583     return BitBlend;
9584
9585   // Check whether a compaction lowering can be done. This handles shuffles
9586   // which take every Nth element for some even N. See the helper function for
9587   // details.
9588   //
9589   // We special case these as they can be particularly efficiently handled with
9590   // the PACKUSB instruction on x86 and they show up in common patterns of
9591   // rearranging bytes to truncate wide elements.
9592   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9593     // NumEvenDrops is the power of two stride of the elements. Another way of
9594     // thinking about it is that we need to drop the even elements this many
9595     // times to get the original input.
9596     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9597
9598     // First we need to zero all the dropped bytes.
9599     assert(NumEvenDrops <= 3 &&
9600            "No support for dropping even elements more than 3 times.");
9601     // We use the mask type to pick which bytes are preserved based on how many
9602     // elements are dropped.
9603     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9604     SDValue ByteClearMask = DAG.getBitcast(
9605         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9606     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9607     if (!IsSingleInput)
9608       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9609
9610     // Now pack things back together.
9611     V1 = DAG.getBitcast(MVT::v8i16, V1);
9612     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9613     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9614     for (int i = 1; i < NumEvenDrops; ++i) {
9615       Result = DAG.getBitcast(MVT::v8i16, Result);
9616       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9617     }
9618
9619     return Result;
9620   }
9621
9622   // Handle multi-input cases by blending single-input shuffles.
9623   if (NumV2Elements > 0)
9624     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9625                                                       Mask, DAG);
9626
9627   // The fallback path for single-input shuffles widens this into two v8i16
9628   // vectors with unpacks, shuffles those, and then pulls them back together
9629   // with a pack.
9630   SDValue V = V1;
9631
9632   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9633   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9634   for (int i = 0; i < 16; ++i)
9635     if (Mask[i] >= 0)
9636       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9637
9638   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9639
9640   SDValue VLoHalf, VHiHalf;
9641   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9642   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9643   // i16s.
9644   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9645                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9646       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9647                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9648     // Use a mask to drop the high bytes.
9649     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9650     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9651                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9652
9653     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9654     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9655
9656     // Squash the masks to point directly into VLoHalf.
9657     for (int &M : LoBlendMask)
9658       if (M >= 0)
9659         M /= 2;
9660     for (int &M : HiBlendMask)
9661       if (M >= 0)
9662         M /= 2;
9663   } else {
9664     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9665     // VHiHalf so that we can blend them as i16s.
9666     VLoHalf = DAG.getBitcast(
9667         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9668     VHiHalf = DAG.getBitcast(
9669         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9670   }
9671
9672   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9673   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9674
9675   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9676 }
9677
9678 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9679 ///
9680 /// This routine breaks down the specific type of 128-bit shuffle and
9681 /// dispatches to the lowering routines accordingly.
9682 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9683                                         MVT VT, const X86Subtarget *Subtarget,
9684                                         SelectionDAG &DAG) {
9685   switch (VT.SimpleTy) {
9686   case MVT::v2i64:
9687     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9688   case MVT::v2f64:
9689     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9690   case MVT::v4i32:
9691     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9692   case MVT::v4f32:
9693     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9694   case MVT::v8i16:
9695     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9696   case MVT::v16i8:
9697     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9698
9699   default:
9700     llvm_unreachable("Unimplemented!");
9701   }
9702 }
9703
9704 /// \brief Helper function to test whether a shuffle mask could be
9705 /// simplified by widening the elements being shuffled.
9706 ///
9707 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9708 /// leaves it in an unspecified state.
9709 ///
9710 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9711 /// shuffle masks. The latter have the special property of a '-2' representing
9712 /// a zero-ed lane of a vector.
9713 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9714                                     SmallVectorImpl<int> &WidenedMask) {
9715   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9716     // If both elements are undef, its trivial.
9717     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9718       WidenedMask.push_back(SM_SentinelUndef);
9719       continue;
9720     }
9721
9722     // Check for an undef mask and a mask value properly aligned to fit with
9723     // a pair of values. If we find such a case, use the non-undef mask's value.
9724     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9725       WidenedMask.push_back(Mask[i + 1] / 2);
9726       continue;
9727     }
9728     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9729       WidenedMask.push_back(Mask[i] / 2);
9730       continue;
9731     }
9732
9733     // When zeroing, we need to spread the zeroing across both lanes to widen.
9734     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9735       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9736           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9737         WidenedMask.push_back(SM_SentinelZero);
9738         continue;
9739       }
9740       return false;
9741     }
9742
9743     // Finally check if the two mask values are adjacent and aligned with
9744     // a pair.
9745     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9746       WidenedMask.push_back(Mask[i] / 2);
9747       continue;
9748     }
9749
9750     // Otherwise we can't safely widen the elements used in this shuffle.
9751     return false;
9752   }
9753   assert(WidenedMask.size() == Mask.size() / 2 &&
9754          "Incorrect size of mask after widening the elements!");
9755
9756   return true;
9757 }
9758
9759 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9760 ///
9761 /// This routine just extracts two subvectors, shuffles them independently, and
9762 /// then concatenates them back together. This should work effectively with all
9763 /// AVX vector shuffle types.
9764 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9765                                           SDValue V2, ArrayRef<int> Mask,
9766                                           SelectionDAG &DAG) {
9767   assert(VT.getSizeInBits() >= 256 &&
9768          "Only for 256-bit or wider vector shuffles!");
9769   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9770   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9771
9772   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9773   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9774
9775   int NumElements = VT.getVectorNumElements();
9776   int SplitNumElements = NumElements / 2;
9777   MVT ScalarVT = VT.getVectorElementType();
9778   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9779
9780   // Rather than splitting build-vectors, just build two narrower build
9781   // vectors. This helps shuffling with splats and zeros.
9782   auto SplitVector = [&](SDValue V) {
9783     while (V.getOpcode() == ISD::BITCAST)
9784       V = V->getOperand(0);
9785
9786     MVT OrigVT = V.getSimpleValueType();
9787     int OrigNumElements = OrigVT.getVectorNumElements();
9788     int OrigSplitNumElements = OrigNumElements / 2;
9789     MVT OrigScalarVT = OrigVT.getVectorElementType();
9790     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9791
9792     SDValue LoV, HiV;
9793
9794     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9795     if (!BV) {
9796       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9797                         DAG.getIntPtrConstant(0, DL));
9798       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9799                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9800     } else {
9801
9802       SmallVector<SDValue, 16> LoOps, HiOps;
9803       for (int i = 0; i < OrigSplitNumElements; ++i) {
9804         LoOps.push_back(BV->getOperand(i));
9805         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9806       }
9807       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9808       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9809     }
9810     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9811                           DAG.getBitcast(SplitVT, HiV));
9812   };
9813
9814   SDValue LoV1, HiV1, LoV2, HiV2;
9815   std::tie(LoV1, HiV1) = SplitVector(V1);
9816   std::tie(LoV2, HiV2) = SplitVector(V2);
9817
9818   // Now create two 4-way blends of these half-width vectors.
9819   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9820     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9821     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9822     for (int i = 0; i < SplitNumElements; ++i) {
9823       int M = HalfMask[i];
9824       if (M >= NumElements) {
9825         if (M >= NumElements + SplitNumElements)
9826           UseHiV2 = true;
9827         else
9828           UseLoV2 = true;
9829         V2BlendMask.push_back(M - NumElements);
9830         V1BlendMask.push_back(-1);
9831         BlendMask.push_back(SplitNumElements + i);
9832       } else if (M >= 0) {
9833         if (M >= SplitNumElements)
9834           UseHiV1 = true;
9835         else
9836           UseLoV1 = true;
9837         V2BlendMask.push_back(-1);
9838         V1BlendMask.push_back(M);
9839         BlendMask.push_back(i);
9840       } else {
9841         V2BlendMask.push_back(-1);
9842         V1BlendMask.push_back(-1);
9843         BlendMask.push_back(-1);
9844       }
9845     }
9846
9847     // Because the lowering happens after all combining takes place, we need to
9848     // manually combine these blend masks as much as possible so that we create
9849     // a minimal number of high-level vector shuffle nodes.
9850
9851     // First try just blending the halves of V1 or V2.
9852     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9853       return DAG.getUNDEF(SplitVT);
9854     if (!UseLoV2 && !UseHiV2)
9855       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9856     if (!UseLoV1 && !UseHiV1)
9857       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9858
9859     SDValue V1Blend, V2Blend;
9860     if (UseLoV1 && UseHiV1) {
9861       V1Blend =
9862         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9863     } else {
9864       // We only use half of V1 so map the usage down into the final blend mask.
9865       V1Blend = UseLoV1 ? LoV1 : HiV1;
9866       for (int i = 0; i < SplitNumElements; ++i)
9867         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9868           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9869     }
9870     if (UseLoV2 && UseHiV2) {
9871       V2Blend =
9872         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9873     } else {
9874       // We only use half of V2 so map the usage down into the final blend mask.
9875       V2Blend = UseLoV2 ? LoV2 : HiV2;
9876       for (int i = 0; i < SplitNumElements; ++i)
9877         if (BlendMask[i] >= SplitNumElements)
9878           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9879     }
9880     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9881   };
9882   SDValue Lo = HalfBlend(LoMask);
9883   SDValue Hi = HalfBlend(HiMask);
9884   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9885 }
9886
9887 /// \brief Either split a vector in halves or decompose the shuffles and the
9888 /// blend.
9889 ///
9890 /// This is provided as a good fallback for many lowerings of non-single-input
9891 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9892 /// between splitting the shuffle into 128-bit components and stitching those
9893 /// back together vs. extracting the single-input shuffles and blending those
9894 /// results.
9895 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9896                                                 SDValue V2, ArrayRef<int> Mask,
9897                                                 SelectionDAG &DAG) {
9898   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9899                                             "lower single-input shuffles as it "
9900                                             "could then recurse on itself.");
9901   int Size = Mask.size();
9902
9903   // If this can be modeled as a broadcast of two elements followed by a blend,
9904   // prefer that lowering. This is especially important because broadcasts can
9905   // often fold with memory operands.
9906   auto DoBothBroadcast = [&] {
9907     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9908     for (int M : Mask)
9909       if (M >= Size) {
9910         if (V2BroadcastIdx == -1)
9911           V2BroadcastIdx = M - Size;
9912         else if (M - Size != V2BroadcastIdx)
9913           return false;
9914       } else if (M >= 0) {
9915         if (V1BroadcastIdx == -1)
9916           V1BroadcastIdx = M;
9917         else if (M != V1BroadcastIdx)
9918           return false;
9919       }
9920     return true;
9921   };
9922   if (DoBothBroadcast())
9923     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9924                                                       DAG);
9925
9926   // If the inputs all stem from a single 128-bit lane of each input, then we
9927   // split them rather than blending because the split will decompose to
9928   // unusually few instructions.
9929   int LaneCount = VT.getSizeInBits() / 128;
9930   int LaneSize = Size / LaneCount;
9931   SmallBitVector LaneInputs[2];
9932   LaneInputs[0].resize(LaneCount, false);
9933   LaneInputs[1].resize(LaneCount, false);
9934   for (int i = 0; i < Size; ++i)
9935     if (Mask[i] >= 0)
9936       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9937   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9938     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9939
9940   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9941   // that the decomposed single-input shuffles don't end up here.
9942   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9943 }
9944
9945 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9946 /// a permutation and blend of those lanes.
9947 ///
9948 /// This essentially blends the out-of-lane inputs to each lane into the lane
9949 /// from a permuted copy of the vector. This lowering strategy results in four
9950 /// instructions in the worst case for a single-input cross lane shuffle which
9951 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9952 /// of. Special cases for each particular shuffle pattern should be handled
9953 /// prior to trying this lowering.
9954 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9955                                                        SDValue V1, SDValue V2,
9956                                                        ArrayRef<int> Mask,
9957                                                        SelectionDAG &DAG) {
9958   // FIXME: This should probably be generalized for 512-bit vectors as well.
9959   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
9960   int LaneSize = Mask.size() / 2;
9961
9962   // If there are only inputs from one 128-bit lane, splitting will in fact be
9963   // less expensive. The flags track whether the given lane contains an element
9964   // that crosses to another lane.
9965   bool LaneCrossing[2] = {false, false};
9966   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9967     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9968       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9969   if (!LaneCrossing[0] || !LaneCrossing[1])
9970     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9971
9972   if (isSingleInputShuffleMask(Mask)) {
9973     SmallVector<int, 32> FlippedBlendMask;
9974     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9975       FlippedBlendMask.push_back(
9976           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9977                                   ? Mask[i]
9978                                   : Mask[i] % LaneSize +
9979                                         (i / LaneSize) * LaneSize + Size));
9980
9981     // Flip the vector, and blend the results which should now be in-lane. The
9982     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9983     // 5 for the high source. The value 3 selects the high half of source 2 and
9984     // the value 2 selects the low half of source 2. We only use source 2 to
9985     // allow folding it into a memory operand.
9986     unsigned PERMMask = 3 | 2 << 4;
9987     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9988                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9989     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9990   }
9991
9992   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9993   // will be handled by the above logic and a blend of the results, much like
9994   // other patterns in AVX.
9995   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9996 }
9997
9998 /// \brief Handle lowering 2-lane 128-bit shuffles.
9999 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10000                                         SDValue V2, ArrayRef<int> Mask,
10001                                         const X86Subtarget *Subtarget,
10002                                         SelectionDAG &DAG) {
10003   // TODO: If minimizing size and one of the inputs is a zero vector and the
10004   // the zero vector has only one use, we could use a VPERM2X128 to save the
10005   // instruction bytes needed to explicitly generate the zero vector.
10006
10007   // Blends are faster and handle all the non-lane-crossing cases.
10008   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10009                                                 Subtarget, DAG))
10010     return Blend;
10011
10012   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10013   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10014
10015   // If either input operand is a zero vector, use VPERM2X128 because its mask
10016   // allows us to replace the zero input with an implicit zero.
10017   if (!IsV1Zero && !IsV2Zero) {
10018     // Check for patterns which can be matched with a single insert of a 128-bit
10019     // subvector.
10020     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10021     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10022       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10023                                    VT.getVectorNumElements() / 2);
10024       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10025                                 DAG.getIntPtrConstant(0, DL));
10026       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10027                                 OnlyUsesV1 ? V1 : V2,
10028                                 DAG.getIntPtrConstant(0, DL));
10029       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10030     }
10031   }
10032
10033   // Otherwise form a 128-bit permutation. After accounting for undefs,
10034   // convert the 64-bit shuffle mask selection values into 128-bit
10035   // selection bits by dividing the indexes by 2 and shifting into positions
10036   // defined by a vperm2*128 instruction's immediate control byte.
10037
10038   // The immediate permute control byte looks like this:
10039   //    [1:0] - select 128 bits from sources for low half of destination
10040   //    [2]   - ignore
10041   //    [3]   - zero low half of destination
10042   //    [5:4] - select 128 bits from sources for high half of destination
10043   //    [6]   - ignore
10044   //    [7]   - zero high half of destination
10045
10046   int MaskLO = Mask[0];
10047   if (MaskLO == SM_SentinelUndef)
10048     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10049
10050   int MaskHI = Mask[2];
10051   if (MaskHI == SM_SentinelUndef)
10052     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10053
10054   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10055
10056   // If either input is a zero vector, replace it with an undef input.
10057   // Shuffle mask values <  4 are selecting elements of V1.
10058   // Shuffle mask values >= 4 are selecting elements of V2.
10059   // Adjust each half of the permute mask by clearing the half that was
10060   // selecting the zero vector and setting the zero mask bit.
10061   if (IsV1Zero) {
10062     V1 = DAG.getUNDEF(VT);
10063     if (MaskLO < 4)
10064       PermMask = (PermMask & 0xf0) | 0x08;
10065     if (MaskHI < 4)
10066       PermMask = (PermMask & 0x0f) | 0x80;
10067   }
10068   if (IsV2Zero) {
10069     V2 = DAG.getUNDEF(VT);
10070     if (MaskLO >= 4)
10071       PermMask = (PermMask & 0xf0) | 0x08;
10072     if (MaskHI >= 4)
10073       PermMask = (PermMask & 0x0f) | 0x80;
10074   }
10075
10076   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10077                      DAG.getConstant(PermMask, DL, MVT::i8));
10078 }
10079
10080 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10081 /// shuffling each lane.
10082 ///
10083 /// This will only succeed when the result of fixing the 128-bit lanes results
10084 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10085 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10086 /// the lane crosses early and then use simpler shuffles within each lane.
10087 ///
10088 /// FIXME: It might be worthwhile at some point to support this without
10089 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10090 /// in x86 only floating point has interesting non-repeating shuffles, and even
10091 /// those are still *marginally* more expensive.
10092 static SDValue lowerVectorShuffleByMerging128BitLanes(
10093     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10094     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10095   assert(!isSingleInputShuffleMask(Mask) &&
10096          "This is only useful with multiple inputs.");
10097
10098   int Size = Mask.size();
10099   int LaneSize = 128 / VT.getScalarSizeInBits();
10100   int NumLanes = Size / LaneSize;
10101   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10102
10103   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10104   // check whether the in-128-bit lane shuffles share a repeating pattern.
10105   SmallVector<int, 4> Lanes;
10106   Lanes.resize(NumLanes, -1);
10107   SmallVector<int, 4> InLaneMask;
10108   InLaneMask.resize(LaneSize, -1);
10109   for (int i = 0; i < Size; ++i) {
10110     if (Mask[i] < 0)
10111       continue;
10112
10113     int j = i / LaneSize;
10114
10115     if (Lanes[j] < 0) {
10116       // First entry we've seen for this lane.
10117       Lanes[j] = Mask[i] / LaneSize;
10118     } else if (Lanes[j] != Mask[i] / LaneSize) {
10119       // This doesn't match the lane selected previously!
10120       return SDValue();
10121     }
10122
10123     // Check that within each lane we have a consistent shuffle mask.
10124     int k = i % LaneSize;
10125     if (InLaneMask[k] < 0) {
10126       InLaneMask[k] = Mask[i] % LaneSize;
10127     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10128       // This doesn't fit a repeating in-lane mask.
10129       return SDValue();
10130     }
10131   }
10132
10133   // First shuffle the lanes into place.
10134   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10135                                 VT.getSizeInBits() / 64);
10136   SmallVector<int, 8> LaneMask;
10137   LaneMask.resize(NumLanes * 2, -1);
10138   for (int i = 0; i < NumLanes; ++i)
10139     if (Lanes[i] >= 0) {
10140       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10141       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10142     }
10143
10144   V1 = DAG.getBitcast(LaneVT, V1);
10145   V2 = DAG.getBitcast(LaneVT, V2);
10146   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10147
10148   // Cast it back to the type we actually want.
10149   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10150
10151   // Now do a simple shuffle that isn't lane crossing.
10152   SmallVector<int, 8> NewMask;
10153   NewMask.resize(Size, -1);
10154   for (int i = 0; i < Size; ++i)
10155     if (Mask[i] >= 0)
10156       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10157   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10158          "Must not introduce lane crosses at this point!");
10159
10160   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10161 }
10162
10163 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10164 /// given mask.
10165 ///
10166 /// This returns true if the elements from a particular input are already in the
10167 /// slot required by the given mask and require no permutation.
10168 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10169   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10170   int Size = Mask.size();
10171   for (int i = 0; i < Size; ++i)
10172     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10173       return false;
10174
10175   return true;
10176 }
10177
10178 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10179                                             ArrayRef<int> Mask, SDValue V1,
10180                                             SDValue V2, SelectionDAG &DAG) {
10181
10182   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10183   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10184   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10185   int NumElts = VT.getVectorNumElements();
10186   bool ShufpdMask = true;
10187   bool CommutableMask = true;
10188   unsigned Immediate = 0;
10189   for (int i = 0; i < NumElts; ++i) {
10190     if (Mask[i] < 0)
10191       continue;
10192     int Val = (i & 6) + NumElts * (i & 1);
10193     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10194     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10195       ShufpdMask = false;
10196     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10197       CommutableMask = false;
10198     Immediate |= (Mask[i] % 2) << i;
10199   }
10200   if (ShufpdMask)
10201     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10202                        DAG.getConstant(Immediate, DL, MVT::i8));
10203   if (CommutableMask)
10204     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10205                        DAG.getConstant(Immediate, DL, MVT::i8));
10206   return SDValue();
10207 }
10208
10209 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10210 ///
10211 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10212 /// isn't available.
10213 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10214                                        const X86Subtarget *Subtarget,
10215                                        SelectionDAG &DAG) {
10216   SDLoc DL(Op);
10217   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10218   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10219   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10220   ArrayRef<int> Mask = SVOp->getMask();
10221   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10222
10223   SmallVector<int, 4> WidenedMask;
10224   if (canWidenShuffleElements(Mask, WidenedMask))
10225     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10226                                     DAG);
10227
10228   if (isSingleInputShuffleMask(Mask)) {
10229     // Check for being able to broadcast a single element.
10230     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10231                                                           Mask, Subtarget, DAG))
10232       return Broadcast;
10233
10234     // Use low duplicate instructions for masks that match their pattern.
10235     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10236       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10237
10238     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10239       // Non-half-crossing single input shuffles can be lowerid with an
10240       // interleaved permutation.
10241       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10242                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10243       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10244                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10245     }
10246
10247     // With AVX2 we have direct support for this permutation.
10248     if (Subtarget->hasAVX2())
10249       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10250                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10251
10252     // Otherwise, fall back.
10253     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10254                                                    DAG);
10255   }
10256
10257   // Use dedicated unpack instructions for masks that match their pattern.
10258   if (SDValue V =
10259           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10260     return V;
10261
10262   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10263                                                 Subtarget, DAG))
10264     return Blend;
10265
10266   // Check if the blend happens to exactly fit that of SHUFPD.
10267   if (SDValue Op =
10268       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10269     return Op;
10270
10271   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10272   // shuffle. However, if we have AVX2 and either inputs are already in place,
10273   // we will be able to shuffle even across lanes the other input in a single
10274   // instruction so skip this pattern.
10275   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10276                                  isShuffleMaskInputInPlace(1, Mask))))
10277     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10278             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10279       return Result;
10280
10281   // If we have AVX2 then we always want to lower with a blend because an v4 we
10282   // can fully permute the elements.
10283   if (Subtarget->hasAVX2())
10284     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10285                                                       Mask, DAG);
10286
10287   // Otherwise fall back on generic lowering.
10288   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10289 }
10290
10291 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10292 ///
10293 /// This routine is only called when we have AVX2 and thus a reasonable
10294 /// instruction set for v4i64 shuffling..
10295 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10296                                        const X86Subtarget *Subtarget,
10297                                        SelectionDAG &DAG) {
10298   SDLoc DL(Op);
10299   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10300   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10302   ArrayRef<int> Mask = SVOp->getMask();
10303   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10304   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10305
10306   SmallVector<int, 4> WidenedMask;
10307   if (canWidenShuffleElements(Mask, WidenedMask))
10308     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10309                                     DAG);
10310
10311   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10312                                                 Subtarget, DAG))
10313     return Blend;
10314
10315   // Check for being able to broadcast a single element.
10316   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10317                                                         Mask, Subtarget, DAG))
10318     return Broadcast;
10319
10320   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10321   // use lower latency instructions that will operate on both 128-bit lanes.
10322   SmallVector<int, 2> RepeatedMask;
10323   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10324     if (isSingleInputShuffleMask(Mask)) {
10325       int PSHUFDMask[] = {-1, -1, -1, -1};
10326       for (int i = 0; i < 2; ++i)
10327         if (RepeatedMask[i] >= 0) {
10328           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10329           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10330         }
10331       return DAG.getBitcast(
10332           MVT::v4i64,
10333           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10334                       DAG.getBitcast(MVT::v8i32, V1),
10335                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10336     }
10337   }
10338
10339   // AVX2 provides a direct instruction for permuting a single input across
10340   // lanes.
10341   if (isSingleInputShuffleMask(Mask))
10342     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10343                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10344
10345   // Try to use shift instructions.
10346   if (SDValue Shift =
10347           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10348     return Shift;
10349
10350   // Use dedicated unpack instructions for masks that match their pattern.
10351   if (SDValue V =
10352           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10353     return V;
10354
10355   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10356   // shuffle. However, if we have AVX2 and either inputs are already in place,
10357   // we will be able to shuffle even across lanes the other input in a single
10358   // instruction so skip this pattern.
10359   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10360                                  isShuffleMaskInputInPlace(1, Mask))))
10361     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10362             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10363       return Result;
10364
10365   // Otherwise fall back on generic blend lowering.
10366   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10367                                                     Mask, DAG);
10368 }
10369
10370 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10371 ///
10372 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10373 /// isn't available.
10374 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10375                                        const X86Subtarget *Subtarget,
10376                                        SelectionDAG &DAG) {
10377   SDLoc DL(Op);
10378   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10379   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10380   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10381   ArrayRef<int> Mask = SVOp->getMask();
10382   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10383
10384   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10385                                                 Subtarget, DAG))
10386     return Blend;
10387
10388   // Check for being able to broadcast a single element.
10389   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10390                                                         Mask, Subtarget, DAG))
10391     return Broadcast;
10392
10393   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10394   // options to efficiently lower the shuffle.
10395   SmallVector<int, 4> RepeatedMask;
10396   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10397     assert(RepeatedMask.size() == 4 &&
10398            "Repeated masks must be half the mask width!");
10399
10400     // Use even/odd duplicate instructions for masks that match their pattern.
10401     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10402       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10403     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10404       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10405
10406     if (isSingleInputShuffleMask(Mask))
10407       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10408                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10409
10410     // Use dedicated unpack instructions for masks that match their pattern.
10411     if (SDValue V =
10412             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10413       return V;
10414
10415     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10416     // have already handled any direct blends. We also need to squash the
10417     // repeated mask into a simulated v4f32 mask.
10418     for (int i = 0; i < 4; ++i)
10419       if (RepeatedMask[i] >= 8)
10420         RepeatedMask[i] -= 4;
10421     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10422   }
10423
10424   // If we have a single input shuffle with different shuffle patterns in the
10425   // two 128-bit lanes use the variable mask to VPERMILPS.
10426   if (isSingleInputShuffleMask(Mask)) {
10427     SDValue VPermMask[8];
10428     for (int i = 0; i < 8; ++i)
10429       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10430                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10431     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10432       return DAG.getNode(
10433           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10434           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10435
10436     if (Subtarget->hasAVX2())
10437       return DAG.getNode(
10438           X86ISD::VPERMV, DL, MVT::v8f32,
10439           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10440                                                  MVT::v8i32, VPermMask)),
10441           V1);
10442
10443     // Otherwise, fall back.
10444     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10445                                                    DAG);
10446   }
10447
10448   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10449   // shuffle.
10450   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10451           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10452     return Result;
10453
10454   // If we have AVX2 then we always want to lower with a blend because at v8 we
10455   // can fully permute the elements.
10456   if (Subtarget->hasAVX2())
10457     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10458                                                       Mask, DAG);
10459
10460   // Otherwise fall back on generic lowering.
10461   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10462 }
10463
10464 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10465 ///
10466 /// This routine is only called when we have AVX2 and thus a reasonable
10467 /// instruction set for v8i32 shuffling..
10468 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10469                                        const X86Subtarget *Subtarget,
10470                                        SelectionDAG &DAG) {
10471   SDLoc DL(Op);
10472   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10473   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10474   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10475   ArrayRef<int> Mask = SVOp->getMask();
10476   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10477   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10478
10479   // Whenever we can lower this as a zext, that instruction is strictly faster
10480   // than any alternative. It also allows us to fold memory operands into the
10481   // shuffle in many cases.
10482   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10483                                                          Mask, Subtarget, DAG))
10484     return ZExt;
10485
10486   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10487                                                 Subtarget, DAG))
10488     return Blend;
10489
10490   // Check for being able to broadcast a single element.
10491   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10492                                                         Mask, Subtarget, DAG))
10493     return Broadcast;
10494
10495   // If the shuffle mask is repeated in each 128-bit lane we can use more
10496   // efficient instructions that mirror the shuffles across the two 128-bit
10497   // lanes.
10498   SmallVector<int, 4> RepeatedMask;
10499   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10500     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10501     if (isSingleInputShuffleMask(Mask))
10502       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10503                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10504
10505     // Use dedicated unpack instructions for masks that match their pattern.
10506     if (SDValue V =
10507             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10508       return V;
10509   }
10510
10511   // Try to use shift instructions.
10512   if (SDValue Shift =
10513           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10514     return Shift;
10515
10516   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10517           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10518     return Rotate;
10519
10520   // If the shuffle patterns aren't repeated but it is a single input, directly
10521   // generate a cross-lane VPERMD instruction.
10522   if (isSingleInputShuffleMask(Mask)) {
10523     SDValue VPermMask[8];
10524     for (int i = 0; i < 8; ++i)
10525       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10526                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10527     return DAG.getNode(
10528         X86ISD::VPERMV, DL, MVT::v8i32,
10529         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10530   }
10531
10532   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10533   // shuffle.
10534   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10535           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10536     return Result;
10537
10538   // Otherwise fall back on generic blend lowering.
10539   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10540                                                     Mask, DAG);
10541 }
10542
10543 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10544 ///
10545 /// This routine is only called when we have AVX2 and thus a reasonable
10546 /// instruction set for v16i16 shuffling..
10547 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10548                                         const X86Subtarget *Subtarget,
10549                                         SelectionDAG &DAG) {
10550   SDLoc DL(Op);
10551   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10552   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10553   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10554   ArrayRef<int> Mask = SVOp->getMask();
10555   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10556   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10557
10558   // Whenever we can lower this as a zext, that instruction is strictly faster
10559   // than any alternative. It also allows us to fold memory operands into the
10560   // shuffle in many cases.
10561   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10562                                                          Mask, Subtarget, DAG))
10563     return ZExt;
10564
10565   // Check for being able to broadcast a single element.
10566   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10567                                                         Mask, Subtarget, DAG))
10568     return Broadcast;
10569
10570   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10571                                                 Subtarget, DAG))
10572     return Blend;
10573
10574   // Use dedicated unpack instructions for masks that match their pattern.
10575   if (SDValue V =
10576           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10577     return V;
10578
10579   // Try to use shift instructions.
10580   if (SDValue Shift =
10581           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10582     return Shift;
10583
10584   // Try to use byte rotation instructions.
10585   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10586           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10587     return Rotate;
10588
10589   if (isSingleInputShuffleMask(Mask)) {
10590     // There are no generalized cross-lane shuffle operations available on i16
10591     // element types.
10592     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10593       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10594                                                      Mask, DAG);
10595
10596     SmallVector<int, 8> RepeatedMask;
10597     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10598       // As this is a single-input shuffle, the repeated mask should be
10599       // a strictly valid v8i16 mask that we can pass through to the v8i16
10600       // lowering to handle even the v16 case.
10601       return lowerV8I16GeneralSingleInputVectorShuffle(
10602           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10603     }
10604
10605     SDValue PSHUFBMask[32];
10606     for (int i = 0; i < 16; ++i) {
10607       if (Mask[i] == -1) {
10608         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10609         continue;
10610       }
10611
10612       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10613       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10614       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10615       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10616     }
10617     return DAG.getBitcast(MVT::v16i16,
10618                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10619                                       DAG.getBitcast(MVT::v32i8, V1),
10620                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10621                                                   MVT::v32i8, PSHUFBMask)));
10622   }
10623
10624   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10625   // shuffle.
10626   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10627           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10628     return Result;
10629
10630   // Otherwise fall back on generic lowering.
10631   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10632 }
10633
10634 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10635 ///
10636 /// This routine is only called when we have AVX2 and thus a reasonable
10637 /// instruction set for v32i8 shuffling..
10638 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10639                                        const X86Subtarget *Subtarget,
10640                                        SelectionDAG &DAG) {
10641   SDLoc DL(Op);
10642   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10643   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10644   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10645   ArrayRef<int> Mask = SVOp->getMask();
10646   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10647   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10648
10649   // Whenever we can lower this as a zext, that instruction is strictly faster
10650   // than any alternative. It also allows us to fold memory operands into the
10651   // shuffle in many cases.
10652   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10653                                                          Mask, Subtarget, DAG))
10654     return ZExt;
10655
10656   // Check for being able to broadcast a single element.
10657   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10658                                                         Mask, Subtarget, DAG))
10659     return Broadcast;
10660
10661   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10662                                                 Subtarget, DAG))
10663     return Blend;
10664
10665   // Use dedicated unpack instructions for masks that match their pattern.
10666   if (SDValue V =
10667           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10668     return V;
10669
10670   // Try to use shift instructions.
10671   if (SDValue Shift =
10672           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10673     return Shift;
10674
10675   // Try to use byte rotation instructions.
10676   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10677           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10678     return Rotate;
10679
10680   if (isSingleInputShuffleMask(Mask)) {
10681     // There are no generalized cross-lane shuffle operations available on i8
10682     // element types.
10683     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10684       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10685                                                      Mask, DAG);
10686
10687     SDValue PSHUFBMask[32];
10688     for (int i = 0; i < 32; ++i)
10689       PSHUFBMask[i] =
10690           Mask[i] < 0
10691               ? DAG.getUNDEF(MVT::i8)
10692               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10693                                 MVT::i8);
10694
10695     return DAG.getNode(
10696         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10697         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10698   }
10699
10700   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10701   // shuffle.
10702   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10703           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10704     return Result;
10705
10706   // Otherwise fall back on generic lowering.
10707   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10708 }
10709
10710 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10711 ///
10712 /// This routine either breaks down the specific type of a 256-bit x86 vector
10713 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10714 /// together based on the available instructions.
10715 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10716                                         MVT VT, const X86Subtarget *Subtarget,
10717                                         SelectionDAG &DAG) {
10718   SDLoc DL(Op);
10719   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10720   ArrayRef<int> Mask = SVOp->getMask();
10721
10722   // If we have a single input to the zero element, insert that into V1 if we
10723   // can do so cheaply.
10724   int NumElts = VT.getVectorNumElements();
10725   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10726     return M >= NumElts;
10727   });
10728
10729   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10730     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10731                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10732       return Insertion;
10733
10734   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10735   // can check for those subtargets here and avoid much of the subtarget
10736   // querying in the per-vector-type lowering routines. With AVX1 we have
10737   // essentially *zero* ability to manipulate a 256-bit vector with integer
10738   // types. Since we'll use floating point types there eventually, just
10739   // immediately cast everything to a float and operate entirely in that domain.
10740   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10741     int ElementBits = VT.getScalarSizeInBits();
10742     if (ElementBits < 32)
10743       // No floating point type available, decompose into 128-bit vectors.
10744       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10745
10746     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10747                                 VT.getVectorNumElements());
10748     V1 = DAG.getBitcast(FpVT, V1);
10749     V2 = DAG.getBitcast(FpVT, V2);
10750     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10751   }
10752
10753   switch (VT.SimpleTy) {
10754   case MVT::v4f64:
10755     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10756   case MVT::v4i64:
10757     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10758   case MVT::v8f32:
10759     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10760   case MVT::v8i32:
10761     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10762   case MVT::v16i16:
10763     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10764   case MVT::v32i8:
10765     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10766
10767   default:
10768     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10769   }
10770 }
10771
10772 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10773 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10774                                         ArrayRef<int> Mask,
10775                                         SDValue V1, SDValue V2,
10776                                         SelectionDAG &DAG) {
10777   assert(VT.getScalarSizeInBits() == 64 &&
10778          "Unexpected element type size for 128bit shuffle.");
10779
10780   // To handle 256 bit vector requires VLX and most probably
10781   // function lowerV2X128VectorShuffle() is better solution.
10782   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
10783
10784   SmallVector<int, 4> WidenedMask;
10785   if (!canWidenShuffleElements(Mask, WidenedMask))
10786     return SDValue();
10787
10788   // Form a 128-bit permutation.
10789   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10790   // bits defined by a vshuf64x2 instruction's immediate control byte.
10791   unsigned PermMask = 0, Imm = 0;
10792   unsigned ControlBitsNum = WidenedMask.size() / 2;
10793
10794   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10795     if (WidenedMask[i] == SM_SentinelZero)
10796       return SDValue();
10797
10798     // Use first element in place of undef mask.
10799     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10800     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10801   }
10802
10803   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10804                      DAG.getConstant(PermMask, DL, MVT::i8));
10805 }
10806
10807 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10808                                            ArrayRef<int> Mask, SDValue V1,
10809                                            SDValue V2, SelectionDAG &DAG) {
10810
10811   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10812
10813   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10814   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10815
10816   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10817   if (isSingleInputShuffleMask(Mask))
10818     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10819
10820   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10821 }
10822
10823 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10824 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10825                                        const X86Subtarget *Subtarget,
10826                                        SelectionDAG &DAG) {
10827   SDLoc DL(Op);
10828   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10829   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10830   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10831   ArrayRef<int> Mask = SVOp->getMask();
10832   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10833
10834   if (SDValue Shuf128 =
10835           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10836     return Shuf128;
10837
10838   if (SDValue Unpck =
10839           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10840     return Unpck;
10841
10842   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10843 }
10844
10845 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10846 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10847                                         const X86Subtarget *Subtarget,
10848                                         SelectionDAG &DAG) {
10849   SDLoc DL(Op);
10850   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10851   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10852   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10853   ArrayRef<int> Mask = SVOp->getMask();
10854   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10855
10856   if (SDValue Unpck =
10857           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10858     return Unpck;
10859
10860   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10861 }
10862
10863 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10864 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10865                                        const X86Subtarget *Subtarget,
10866                                        SelectionDAG &DAG) {
10867   SDLoc DL(Op);
10868   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10869   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10871   ArrayRef<int> Mask = SVOp->getMask();
10872   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10873
10874   if (SDValue Shuf128 =
10875           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10876     return Shuf128;
10877
10878   if (SDValue Unpck =
10879           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10880     return Unpck;
10881
10882   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10883 }
10884
10885 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10886 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10887                                         const X86Subtarget *Subtarget,
10888                                         SelectionDAG &DAG) {
10889   SDLoc DL(Op);
10890   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10891   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10892   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10893   ArrayRef<int> Mask = SVOp->getMask();
10894   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10895
10896   if (SDValue Unpck =
10897           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10898     return Unpck;
10899
10900   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10901 }
10902
10903 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10904 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10905                                         const X86Subtarget *Subtarget,
10906                                         SelectionDAG &DAG) {
10907   SDLoc DL(Op);
10908   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10909   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10910   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10911   ArrayRef<int> Mask = SVOp->getMask();
10912   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10913   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10914
10915   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10916 }
10917
10918 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10919 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10920                                        const X86Subtarget *Subtarget,
10921                                        SelectionDAG &DAG) {
10922   SDLoc DL(Op);
10923   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10924   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10925   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10926   ArrayRef<int> Mask = SVOp->getMask();
10927   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10928   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10929
10930   // FIXME: Implement direct support for this type!
10931   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10932 }
10933
10934 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10935 ///
10936 /// This routine either breaks down the specific type of a 512-bit x86 vector
10937 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10938 /// together based on the available instructions.
10939 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10940                                         MVT VT, const X86Subtarget *Subtarget,
10941                                         SelectionDAG &DAG) {
10942   SDLoc DL(Op);
10943   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10944   ArrayRef<int> Mask = SVOp->getMask();
10945   assert(Subtarget->hasAVX512() &&
10946          "Cannot lower 512-bit vectors w/ basic ISA!");
10947
10948   // Check for being able to broadcast a single element.
10949   if (SDValue Broadcast =
10950           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10951     return Broadcast;
10952
10953   // Dispatch to each element type for lowering. If we don't have supprot for
10954   // specific element type shuffles at 512 bits, immediately split them and
10955   // lower them. Each lowering routine of a given type is allowed to assume that
10956   // the requisite ISA extensions for that element type are available.
10957   switch (VT.SimpleTy) {
10958   case MVT::v8f64:
10959     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10960   case MVT::v16f32:
10961     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10962   case MVT::v8i64:
10963     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10964   case MVT::v16i32:
10965     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10966   case MVT::v32i16:
10967     if (Subtarget->hasBWI())
10968       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10969     break;
10970   case MVT::v64i8:
10971     if (Subtarget->hasBWI())
10972       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10973     break;
10974
10975   default:
10976     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10977   }
10978
10979   // Otherwise fall back on splitting.
10980   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10981 }
10982
10983 // Lower vXi1 vector shuffles.
10984 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10985 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10986 // vector, shuffle and then truncate it back.
10987 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10988                                       MVT VT, const X86Subtarget *Subtarget,
10989                                       SelectionDAG &DAG) {
10990   SDLoc DL(Op);
10991   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10992   ArrayRef<int> Mask = SVOp->getMask();
10993   assert(Subtarget->hasAVX512() &&
10994          "Cannot lower 512-bit vectors w/o basic ISA!");
10995   MVT ExtVT;
10996   switch (VT.SimpleTy) {
10997   default:
10998     llvm_unreachable("Expected a vector of i1 elements");
10999   case MVT::v2i1:
11000     ExtVT = MVT::v2i64;
11001     break;
11002   case MVT::v4i1:
11003     ExtVT = MVT::v4i32;
11004     break;
11005   case MVT::v8i1:
11006     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11007     break;
11008   case MVT::v16i1:
11009     ExtVT = MVT::v16i32;
11010     break;
11011   case MVT::v32i1:
11012     ExtVT = MVT::v32i16;
11013     break;
11014   case MVT::v64i1:
11015     ExtVT = MVT::v64i8;
11016     break;
11017   }
11018
11019   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11020     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11021   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11022     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11023   else
11024     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11025
11026   if (V2.isUndef())
11027     V2 = DAG.getUNDEF(ExtVT);
11028   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11029     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11030   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11031     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11032   else
11033     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11034   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11035                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11036 }
11037 /// \brief Top-level lowering for x86 vector shuffles.
11038 ///
11039 /// This handles decomposition, canonicalization, and lowering of all x86
11040 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11041 /// above in helper routines. The canonicalization attempts to widen shuffles
11042 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11043 /// s.t. only one of the two inputs needs to be tested, etc.
11044 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11045                                   SelectionDAG &DAG) {
11046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11047   ArrayRef<int> Mask = SVOp->getMask();
11048   SDValue V1 = Op.getOperand(0);
11049   SDValue V2 = Op.getOperand(1);
11050   MVT VT = Op.getSimpleValueType();
11051   int NumElements = VT.getVectorNumElements();
11052   SDLoc dl(Op);
11053   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11054
11055   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11056          "Can't lower MMX shuffles");
11057
11058   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11059   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11060   if (V1IsUndef && V2IsUndef)
11061     return DAG.getUNDEF(VT);
11062
11063   // When we create a shuffle node we put the UNDEF node to second operand,
11064   // but in some cases the first operand may be transformed to UNDEF.
11065   // In this case we should just commute the node.
11066   if (V1IsUndef)
11067     return DAG.getCommutedVectorShuffle(*SVOp);
11068
11069   // Check for non-undef masks pointing at an undef vector and make the masks
11070   // undef as well. This makes it easier to match the shuffle based solely on
11071   // the mask.
11072   if (V2IsUndef)
11073     for (int M : Mask)
11074       if (M >= NumElements) {
11075         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11076         for (int &M : NewMask)
11077           if (M >= NumElements)
11078             M = -1;
11079         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11080       }
11081
11082   // We actually see shuffles that are entirely re-arrangements of a set of
11083   // zero inputs. This mostly happens while decomposing complex shuffles into
11084   // simple ones. Directly lower these as a buildvector of zeros.
11085   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11086   if (Zeroable.all())
11087     return getZeroVector(VT, Subtarget, DAG, dl);
11088
11089   // Try to collapse shuffles into using a vector type with fewer elements but
11090   // wider element types. We cap this to not form integers or floating point
11091   // elements wider than 64 bits, but it might be interesting to form i128
11092   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11093   SmallVector<int, 16> WidenedMask;
11094   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11095       canWidenShuffleElements(Mask, WidenedMask)) {
11096     MVT NewEltVT = VT.isFloatingPoint()
11097                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11098                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11099     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11100     // Make sure that the new vector type is legal. For example, v2f64 isn't
11101     // legal on SSE1.
11102     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11103       V1 = DAG.getBitcast(NewVT, V1);
11104       V2 = DAG.getBitcast(NewVT, V2);
11105       return DAG.getBitcast(
11106           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11107     }
11108   }
11109
11110   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11111   for (int M : SVOp->getMask())
11112     if (M < 0)
11113       ++NumUndefElements;
11114     else if (M < NumElements)
11115       ++NumV1Elements;
11116     else
11117       ++NumV2Elements;
11118
11119   // Commute the shuffle as needed such that more elements come from V1 than
11120   // V2. This allows us to match the shuffle pattern strictly on how many
11121   // elements come from V1 without handling the symmetric cases.
11122   if (NumV2Elements > NumV1Elements)
11123     return DAG.getCommutedVectorShuffle(*SVOp);
11124
11125   // When the number of V1 and V2 elements are the same, try to minimize the
11126   // number of uses of V2 in the low half of the vector. When that is tied,
11127   // ensure that the sum of indices for V1 is equal to or lower than the sum
11128   // indices for V2. When those are equal, try to ensure that the number of odd
11129   // indices for V1 is lower than the number of odd indices for V2.
11130   if (NumV1Elements == NumV2Elements) {
11131     int LowV1Elements = 0, LowV2Elements = 0;
11132     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11133       if (M >= NumElements)
11134         ++LowV2Elements;
11135       else if (M >= 0)
11136         ++LowV1Elements;
11137     if (LowV2Elements > LowV1Elements) {
11138       return DAG.getCommutedVectorShuffle(*SVOp);
11139     } else if (LowV2Elements == LowV1Elements) {
11140       int SumV1Indices = 0, SumV2Indices = 0;
11141       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11142         if (SVOp->getMask()[i] >= NumElements)
11143           SumV2Indices += i;
11144         else if (SVOp->getMask()[i] >= 0)
11145           SumV1Indices += i;
11146       if (SumV2Indices < SumV1Indices) {
11147         return DAG.getCommutedVectorShuffle(*SVOp);
11148       } else if (SumV2Indices == SumV1Indices) {
11149         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11150         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11151           if (SVOp->getMask()[i] >= NumElements)
11152             NumV2OddIndices += i % 2;
11153           else if (SVOp->getMask()[i] >= 0)
11154             NumV1OddIndices += i % 2;
11155         if (NumV2OddIndices < NumV1OddIndices)
11156           return DAG.getCommutedVectorShuffle(*SVOp);
11157       }
11158     }
11159   }
11160
11161   // For each vector width, delegate to a specialized lowering routine.
11162   if (VT.is128BitVector())
11163     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11164
11165   if (VT.is256BitVector())
11166     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11167
11168   if (VT.is512BitVector())
11169     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11170
11171   if (Is1BitVector)
11172     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11173   llvm_unreachable("Unimplemented!");
11174 }
11175
11176 // This function assumes its argument is a BUILD_VECTOR of constants or
11177 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11178 // true.
11179 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11180                                     unsigned &MaskValue) {
11181   MaskValue = 0;
11182   unsigned NumElems = BuildVector->getNumOperands();
11183
11184   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11185   // We don't handle the >2 lanes case right now.
11186   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11187   if (NumLanes > 2)
11188     return false;
11189
11190   unsigned NumElemsInLane = NumElems / NumLanes;
11191
11192   // Blend for v16i16 should be symmetric for the both lanes.
11193   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11194     SDValue EltCond = BuildVector->getOperand(i);
11195     SDValue SndLaneEltCond =
11196         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11197
11198     int Lane1Cond = -1, Lane2Cond = -1;
11199     if (isa<ConstantSDNode>(EltCond))
11200       Lane1Cond = !isZero(EltCond);
11201     if (isa<ConstantSDNode>(SndLaneEltCond))
11202       Lane2Cond = !isZero(SndLaneEltCond);
11203
11204     unsigned LaneMask = 0;
11205     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11206       // Lane1Cond != 0, means we want the first argument.
11207       // Lane1Cond == 0, means we want the second argument.
11208       // The encoding of this argument is 0 for the first argument, 1
11209       // for the second. Therefore, invert the condition.
11210       LaneMask = !Lane1Cond << i;
11211     else if (Lane1Cond < 0)
11212       LaneMask = !Lane2Cond << i;
11213     else
11214       return false;
11215
11216     MaskValue |= LaneMask;
11217     if (NumLanes == 2)
11218       MaskValue |= LaneMask << NumElemsInLane;
11219   }
11220   return true;
11221 }
11222
11223 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11224 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11225                                            const X86Subtarget *Subtarget,
11226                                            SelectionDAG &DAG) {
11227   SDValue Cond = Op.getOperand(0);
11228   SDValue LHS = Op.getOperand(1);
11229   SDValue RHS = Op.getOperand(2);
11230   SDLoc dl(Op);
11231   MVT VT = Op.getSimpleValueType();
11232
11233   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11234     return SDValue();
11235   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11236
11237   // Only non-legal VSELECTs reach this lowering, convert those into generic
11238   // shuffles and re-use the shuffle lowering path for blends.
11239   SmallVector<int, 32> Mask;
11240   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11241     SDValue CondElt = CondBV->getOperand(i);
11242     Mask.push_back(
11243         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11244   }
11245   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11246 }
11247
11248 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11249   // A vselect where all conditions and data are constants can be optimized into
11250   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11251   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11252       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11253       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11254     return SDValue();
11255
11256   // Try to lower this to a blend-style vector shuffle. This can handle all
11257   // constant condition cases.
11258   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11259     return BlendOp;
11260
11261   // Variable blends are only legal from SSE4.1 onward.
11262   if (!Subtarget->hasSSE41())
11263     return SDValue();
11264
11265   // Only some types will be legal on some subtargets. If we can emit a legal
11266   // VSELECT-matching blend, return Op, and but if we need to expand, return
11267   // a null value.
11268   switch (Op.getSimpleValueType().SimpleTy) {
11269   default:
11270     // Most of the vector types have blends past SSE4.1.
11271     return Op;
11272
11273   case MVT::v32i8:
11274     // The byte blends for AVX vectors were introduced only in AVX2.
11275     if (Subtarget->hasAVX2())
11276       return Op;
11277
11278     return SDValue();
11279
11280   case MVT::v8i16:
11281   case MVT::v16i16:
11282     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11283     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11284       return Op;
11285
11286     // FIXME: We should custom lower this by fixing the condition and using i8
11287     // blends.
11288     return SDValue();
11289   }
11290 }
11291
11292 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11293   MVT VT = Op.getSimpleValueType();
11294   SDLoc dl(Op);
11295
11296   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11297     return SDValue();
11298
11299   if (VT.getSizeInBits() == 8) {
11300     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11301                                   Op.getOperand(0), Op.getOperand(1));
11302     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11303                                   DAG.getValueType(VT));
11304     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11305   }
11306
11307   if (VT.getSizeInBits() == 16) {
11308     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11309     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11310     if (Idx == 0)
11311       return DAG.getNode(
11312           ISD::TRUNCATE, dl, MVT::i16,
11313           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11314                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11315                       Op.getOperand(1)));
11316     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11317                                   Op.getOperand(0), Op.getOperand(1));
11318     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11319                                   DAG.getValueType(VT));
11320     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11321   }
11322
11323   if (VT == MVT::f32) {
11324     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11325     // the result back to FR32 register. It's only worth matching if the
11326     // result has a single use which is a store or a bitcast to i32.  And in
11327     // the case of a store, it's not worth it if the index is a constant 0,
11328     // because a MOVSSmr can be used instead, which is smaller and faster.
11329     if (!Op.hasOneUse())
11330       return SDValue();
11331     SDNode *User = *Op.getNode()->use_begin();
11332     if ((User->getOpcode() != ISD::STORE ||
11333          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11334           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11335         (User->getOpcode() != ISD::BITCAST ||
11336          User->getValueType(0) != MVT::i32))
11337       return SDValue();
11338     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11339                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11340                                   Op.getOperand(1));
11341     return DAG.getBitcast(MVT::f32, Extract);
11342   }
11343
11344   if (VT == MVT::i32 || VT == MVT::i64) {
11345     // ExtractPS/pextrq works with constant index.
11346     if (isa<ConstantSDNode>(Op.getOperand(1)))
11347       return Op;
11348   }
11349   return SDValue();
11350 }
11351
11352 /// Extract one bit from mask vector, like v16i1 or v8i1.
11353 /// AVX-512 feature.
11354 SDValue
11355 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11356   SDValue Vec = Op.getOperand(0);
11357   SDLoc dl(Vec);
11358   MVT VecVT = Vec.getSimpleValueType();
11359   SDValue Idx = Op.getOperand(1);
11360   MVT EltVT = Op.getSimpleValueType();
11361
11362   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11363   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11364          "Unexpected vector type in ExtractBitFromMaskVector");
11365
11366   // variable index can't be handled in mask registers,
11367   // extend vector to VR512
11368   if (!isa<ConstantSDNode>(Idx)) {
11369     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11370     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11371     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11372                               ExtVT.getVectorElementType(), Ext, Idx);
11373     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11374   }
11375
11376   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11377   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11378   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11379     rc = getRegClassFor(MVT::v16i1);
11380   unsigned MaxSift = rc->getSize()*8 - 1;
11381   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11382                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11383   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11384                     DAG.getConstant(MaxSift, dl, MVT::i8));
11385   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11386                        DAG.getIntPtrConstant(0, dl));
11387 }
11388
11389 SDValue
11390 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11391                                            SelectionDAG &DAG) const {
11392   SDLoc dl(Op);
11393   SDValue Vec = Op.getOperand(0);
11394   MVT VecVT = Vec.getSimpleValueType();
11395   SDValue Idx = Op.getOperand(1);
11396
11397   if (Op.getSimpleValueType() == MVT::i1)
11398     return ExtractBitFromMaskVector(Op, DAG);
11399
11400   if (!isa<ConstantSDNode>(Idx)) {
11401     if (VecVT.is512BitVector() ||
11402         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11403          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11404
11405       MVT MaskEltVT =
11406         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11407       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11408                                     MaskEltVT.getSizeInBits());
11409
11410       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11411       auto PtrVT = getPointerTy(DAG.getDataLayout());
11412       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11413                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11414                                  DAG.getConstant(0, dl, PtrVT));
11415       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11416       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11417                          DAG.getConstant(0, dl, PtrVT));
11418     }
11419     return SDValue();
11420   }
11421
11422   // If this is a 256-bit vector result, first extract the 128-bit vector and
11423   // then extract the element from the 128-bit vector.
11424   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11425
11426     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11427     // Get the 128-bit vector.
11428     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11429     MVT EltVT = VecVT.getVectorElementType();
11430
11431     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11432     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11433
11434     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11435     // this can be done with a mask.
11436     IdxVal &= ElemsPerChunk - 1;
11437     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11438                        DAG.getConstant(IdxVal, dl, MVT::i32));
11439   }
11440
11441   assert(VecVT.is128BitVector() && "Unexpected vector length");
11442
11443   if (Subtarget->hasSSE41())
11444     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11445       return Res;
11446
11447   MVT VT = Op.getSimpleValueType();
11448   // TODO: handle v16i8.
11449   if (VT.getSizeInBits() == 16) {
11450     SDValue Vec = Op.getOperand(0);
11451     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11452     if (Idx == 0)
11453       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11454                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11455                                      DAG.getBitcast(MVT::v4i32, Vec),
11456                                      Op.getOperand(1)));
11457     // Transform it so it match pextrw which produces a 32-bit result.
11458     MVT EltVT = MVT::i32;
11459     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11460                                   Op.getOperand(0), Op.getOperand(1));
11461     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11462                                   DAG.getValueType(VT));
11463     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11464   }
11465
11466   if (VT.getSizeInBits() == 32) {
11467     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11468     if (Idx == 0)
11469       return Op;
11470
11471     // SHUFPS the element to the lowest double word, then movss.
11472     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11473     MVT VVT = Op.getOperand(0).getSimpleValueType();
11474     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11475                                        DAG.getUNDEF(VVT), Mask);
11476     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11477                        DAG.getIntPtrConstant(0, dl));
11478   }
11479
11480   if (VT.getSizeInBits() == 64) {
11481     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11482     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11483     //        to match extract_elt for f64.
11484     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11485     if (Idx == 0)
11486       return Op;
11487
11488     // UNPCKHPD the element to the lowest double word, then movsd.
11489     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11490     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11491     int Mask[2] = { 1, -1 };
11492     MVT VVT = Op.getOperand(0).getSimpleValueType();
11493     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11494                                        DAG.getUNDEF(VVT), Mask);
11495     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11496                        DAG.getIntPtrConstant(0, dl));
11497   }
11498
11499   return SDValue();
11500 }
11501
11502 /// Insert one bit to mask vector, like v16i1 or v8i1.
11503 /// AVX-512 feature.
11504 SDValue
11505 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11506   SDLoc dl(Op);
11507   SDValue Vec = Op.getOperand(0);
11508   SDValue Elt = Op.getOperand(1);
11509   SDValue Idx = Op.getOperand(2);
11510   MVT VecVT = Vec.getSimpleValueType();
11511
11512   if (!isa<ConstantSDNode>(Idx)) {
11513     // Non constant index. Extend source and destination,
11514     // insert element and then truncate the result.
11515     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11516     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11517     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11518       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11519       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11520     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11521   }
11522
11523   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11524   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11525   if (IdxVal)
11526     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11527                            DAG.getConstant(IdxVal, dl, MVT::i8));
11528   if (Vec.getOpcode() == ISD::UNDEF)
11529     return EltInVec;
11530   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11531 }
11532
11533 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11534                                                   SelectionDAG &DAG) const {
11535   MVT VT = Op.getSimpleValueType();
11536   MVT EltVT = VT.getVectorElementType();
11537
11538   if (EltVT == MVT::i1)
11539     return InsertBitToMaskVector(Op, DAG);
11540
11541   SDLoc dl(Op);
11542   SDValue N0 = Op.getOperand(0);
11543   SDValue N1 = Op.getOperand(1);
11544   SDValue N2 = Op.getOperand(2);
11545   if (!isa<ConstantSDNode>(N2))
11546     return SDValue();
11547   auto *N2C = cast<ConstantSDNode>(N2);
11548   unsigned IdxVal = N2C->getZExtValue();
11549
11550   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11551   // into that, and then insert the subvector back into the result.
11552   if (VT.is256BitVector() || VT.is512BitVector()) {
11553     // With a 256-bit vector, we can insert into the zero element efficiently
11554     // using a blend if we have AVX or AVX2 and the right data type.
11555     if (VT.is256BitVector() && IdxVal == 0) {
11556       // TODO: It is worthwhile to cast integer to floating point and back
11557       // and incur a domain crossing penalty if that's what we'll end up
11558       // doing anyway after extracting to a 128-bit vector.
11559       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11560           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11561         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11562         N2 = DAG.getIntPtrConstant(1, dl);
11563         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11564       }
11565     }
11566
11567     // Get the desired 128-bit vector chunk.
11568     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11569
11570     // Insert the element into the desired chunk.
11571     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11572     assert(isPowerOf2_32(NumEltsIn128));
11573     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11574     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11575
11576     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11577                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11578
11579     // Insert the changed part back into the bigger vector
11580     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11581   }
11582   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11583
11584   if (Subtarget->hasSSE41()) {
11585     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11586       unsigned Opc;
11587       if (VT == MVT::v8i16) {
11588         Opc = X86ISD::PINSRW;
11589       } else {
11590         assert(VT == MVT::v16i8);
11591         Opc = X86ISD::PINSRB;
11592       }
11593
11594       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11595       // argument.
11596       if (N1.getValueType() != MVT::i32)
11597         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11598       if (N2.getValueType() != MVT::i32)
11599         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11600       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11601     }
11602
11603     if (EltVT == MVT::f32) {
11604       // Bits [7:6] of the constant are the source select. This will always be
11605       //   zero here. The DAG Combiner may combine an extract_elt index into
11606       //   these bits. For example (insert (extract, 3), 2) could be matched by
11607       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11608       // Bits [5:4] of the constant are the destination select. This is the
11609       //   value of the incoming immediate.
11610       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11611       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11612
11613       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11614       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11615         // If this is an insertion of 32-bits into the low 32-bits of
11616         // a vector, we prefer to generate a blend with immediate rather
11617         // than an insertps. Blends are simpler operations in hardware and so
11618         // will always have equal or better performance than insertps.
11619         // But if optimizing for size and there's a load folding opportunity,
11620         // generate insertps because blendps does not have a 32-bit memory
11621         // operand form.
11622         N2 = DAG.getIntPtrConstant(1, dl);
11623         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11624         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11625       }
11626       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11627       // Create this as a scalar to vector..
11628       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11629       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11630     }
11631
11632     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11633       // PINSR* works with constant index.
11634       return Op;
11635     }
11636   }
11637
11638   if (EltVT == MVT::i8)
11639     return SDValue();
11640
11641   if (EltVT.getSizeInBits() == 16) {
11642     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11643     // as its second argument.
11644     if (N1.getValueType() != MVT::i32)
11645       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11646     if (N2.getValueType() != MVT::i32)
11647       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11648     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11649   }
11650   return SDValue();
11651 }
11652
11653 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11654   SDLoc dl(Op);
11655   MVT OpVT = Op.getSimpleValueType();
11656
11657   // If this is a 256-bit vector result, first insert into a 128-bit
11658   // vector and then insert into the 256-bit vector.
11659   if (!OpVT.is128BitVector()) {
11660     // Insert into a 128-bit vector.
11661     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11662     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11663                                  OpVT.getVectorNumElements() / SizeFactor);
11664
11665     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11666
11667     // Insert the 128-bit vector.
11668     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11669   }
11670
11671   if (OpVT == MVT::v1i64 &&
11672       Op.getOperand(0).getValueType() == MVT::i64)
11673     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11674
11675   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11676   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11677   return DAG.getBitcast(
11678       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11679 }
11680
11681 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11682 // a simple subregister reference or explicit instructions to grab
11683 // upper bits of a vector.
11684 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11685                                       SelectionDAG &DAG) {
11686   SDLoc dl(Op);
11687   SDValue In =  Op.getOperand(0);
11688   SDValue Idx = Op.getOperand(1);
11689   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11690   MVT ResVT   = Op.getSimpleValueType();
11691   MVT InVT    = In.getSimpleValueType();
11692
11693   if (Subtarget->hasFp256()) {
11694     if (ResVT.is128BitVector() &&
11695         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11696         isa<ConstantSDNode>(Idx)) {
11697       return Extract128BitVector(In, IdxVal, DAG, dl);
11698     }
11699     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11700         isa<ConstantSDNode>(Idx)) {
11701       return Extract256BitVector(In, IdxVal, DAG, dl);
11702     }
11703   }
11704   return SDValue();
11705 }
11706
11707 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11708 // simple superregister reference or explicit instructions to insert
11709 // the upper bits of a vector.
11710 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11711                                      SelectionDAG &DAG) {
11712   if (!Subtarget->hasAVX())
11713     return SDValue();
11714
11715   SDLoc dl(Op);
11716   SDValue Vec = Op.getOperand(0);
11717   SDValue SubVec = Op.getOperand(1);
11718   SDValue Idx = Op.getOperand(2);
11719
11720   if (!isa<ConstantSDNode>(Idx))
11721     return SDValue();
11722
11723   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11724   MVT OpVT = Op.getSimpleValueType();
11725   MVT SubVecVT = SubVec.getSimpleValueType();
11726
11727   // Fold two 16-byte subvector loads into one 32-byte load:
11728   // (insert_subvector (insert_subvector undef, (load addr), 0),
11729   //                   (load addr + 16), Elts/2)
11730   // --> load32 addr
11731   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11732       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11733       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11734     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11735     if (Idx2 && Idx2->getZExtValue() == 0) {
11736       SDValue SubVec2 = Vec.getOperand(1);
11737       // If needed, look through a bitcast to get to the load.
11738       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11739         SubVec2 = SubVec2.getOperand(0);
11740
11741       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11742         bool Fast;
11743         unsigned Alignment = FirstLd->getAlignment();
11744         unsigned AS = FirstLd->getAddressSpace();
11745         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11746         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11747                                     OpVT, AS, Alignment, &Fast) && Fast) {
11748           SDValue Ops[] = { SubVec2, SubVec };
11749           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11750             return Ld;
11751         }
11752       }
11753     }
11754   }
11755
11756   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11757       SubVecVT.is128BitVector())
11758     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11759
11760   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11761     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11762
11763   if (OpVT.getVectorElementType() == MVT::i1) {
11764     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11765       return Op;
11766     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11767     SDValue Undef = DAG.getUNDEF(OpVT);
11768     unsigned NumElems = OpVT.getVectorNumElements();
11769     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11770
11771     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11772       // Zero upper bits of the Vec
11773       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11774       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11775
11776       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11777                                  SubVec, ZeroIdx);
11778       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11779       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11780     }
11781     if (IdxVal == 0) {
11782       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11783                                  SubVec, ZeroIdx);
11784       // Zero upper bits of the Vec2
11785       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11786       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11787       // Zero lower bits of the Vec
11788       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11789       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11790       // Merge them together
11791       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11792     }
11793   }
11794   return SDValue();
11795 }
11796
11797 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11798 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11799 // one of the above mentioned nodes. It has to be wrapped because otherwise
11800 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11801 // be used to form addressing mode. These wrapped nodes will be selected
11802 // into MOV32ri.
11803 SDValue
11804 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11805   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11806
11807   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11808   // global base reg.
11809   unsigned char OpFlag = 0;
11810   unsigned WrapperKind = X86ISD::Wrapper;
11811   CodeModel::Model M = DAG.getTarget().getCodeModel();
11812
11813   if (Subtarget->isPICStyleRIPRel() &&
11814       (M == CodeModel::Small || M == CodeModel::Kernel))
11815     WrapperKind = X86ISD::WrapperRIP;
11816   else if (Subtarget->isPICStyleGOT())
11817     OpFlag = X86II::MO_GOTOFF;
11818   else if (Subtarget->isPICStyleStubPIC())
11819     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11820
11821   auto PtrVT = getPointerTy(DAG.getDataLayout());
11822   SDValue Result = DAG.getTargetConstantPool(
11823       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11824   SDLoc DL(CP);
11825   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11826   // With PIC, the address is actually $g + Offset.
11827   if (OpFlag) {
11828     Result =
11829         DAG.getNode(ISD::ADD, DL, PtrVT,
11830                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11831   }
11832
11833   return Result;
11834 }
11835
11836 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11837   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11838
11839   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11840   // global base reg.
11841   unsigned char OpFlag = 0;
11842   unsigned WrapperKind = X86ISD::Wrapper;
11843   CodeModel::Model M = DAG.getTarget().getCodeModel();
11844
11845   if (Subtarget->isPICStyleRIPRel() &&
11846       (M == CodeModel::Small || M == CodeModel::Kernel))
11847     WrapperKind = X86ISD::WrapperRIP;
11848   else if (Subtarget->isPICStyleGOT())
11849     OpFlag = X86II::MO_GOTOFF;
11850   else if (Subtarget->isPICStyleStubPIC())
11851     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11852
11853   auto PtrVT = getPointerTy(DAG.getDataLayout());
11854   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11855   SDLoc DL(JT);
11856   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11857
11858   // With PIC, the address is actually $g + Offset.
11859   if (OpFlag)
11860     Result =
11861         DAG.getNode(ISD::ADD, DL, PtrVT,
11862                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11863
11864   return Result;
11865 }
11866
11867 SDValue
11868 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11869   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11870
11871   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11872   // global base reg.
11873   unsigned char OpFlag = 0;
11874   unsigned WrapperKind = X86ISD::Wrapper;
11875   CodeModel::Model M = DAG.getTarget().getCodeModel();
11876
11877   if (Subtarget->isPICStyleRIPRel() &&
11878       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11879     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11880       OpFlag = X86II::MO_GOTPCREL;
11881     WrapperKind = X86ISD::WrapperRIP;
11882   } else if (Subtarget->isPICStyleGOT()) {
11883     OpFlag = X86II::MO_GOT;
11884   } else if (Subtarget->isPICStyleStubPIC()) {
11885     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11886   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11887     OpFlag = X86II::MO_DARWIN_NONLAZY;
11888   }
11889
11890   auto PtrVT = getPointerTy(DAG.getDataLayout());
11891   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11892
11893   SDLoc DL(Op);
11894   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11895
11896   // With PIC, the address is actually $g + Offset.
11897   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11898       !Subtarget->is64Bit()) {
11899     Result =
11900         DAG.getNode(ISD::ADD, DL, PtrVT,
11901                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11902   }
11903
11904   // For symbols that require a load from a stub to get the address, emit the
11905   // load.
11906   if (isGlobalStubReference(OpFlag))
11907     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11908                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11909                          false, false, false, 0);
11910
11911   return Result;
11912 }
11913
11914 SDValue
11915 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11916   // Create the TargetBlockAddressAddress node.
11917   unsigned char OpFlags =
11918     Subtarget->ClassifyBlockAddressReference();
11919   CodeModel::Model M = DAG.getTarget().getCodeModel();
11920   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11921   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11922   SDLoc dl(Op);
11923   auto PtrVT = getPointerTy(DAG.getDataLayout());
11924   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11925
11926   if (Subtarget->isPICStyleRIPRel() &&
11927       (M == CodeModel::Small || M == CodeModel::Kernel))
11928     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11929   else
11930     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11931
11932   // With PIC, the address is actually $g + Offset.
11933   if (isGlobalRelativeToPICBase(OpFlags)) {
11934     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11935                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11936   }
11937
11938   return Result;
11939 }
11940
11941 SDValue
11942 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11943                                       int64_t Offset, SelectionDAG &DAG) const {
11944   // Create the TargetGlobalAddress node, folding in the constant
11945   // offset if it is legal.
11946   unsigned char OpFlags =
11947       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11948   CodeModel::Model M = DAG.getTarget().getCodeModel();
11949   auto PtrVT = getPointerTy(DAG.getDataLayout());
11950   SDValue Result;
11951   if (OpFlags == X86II::MO_NO_FLAG &&
11952       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11953     // A direct static reference to a global.
11954     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11955     Offset = 0;
11956   } else {
11957     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11958   }
11959
11960   if (Subtarget->isPICStyleRIPRel() &&
11961       (M == CodeModel::Small || M == CodeModel::Kernel))
11962     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11963   else
11964     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11965
11966   // With PIC, the address is actually $g + Offset.
11967   if (isGlobalRelativeToPICBase(OpFlags)) {
11968     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11969                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11970   }
11971
11972   // For globals that require a load from a stub to get the address, emit the
11973   // load.
11974   if (isGlobalStubReference(OpFlags))
11975     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11976                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11977                          false, false, false, 0);
11978
11979   // If there was a non-zero offset that we didn't fold, create an explicit
11980   // addition for it.
11981   if (Offset != 0)
11982     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11983                          DAG.getConstant(Offset, dl, PtrVT));
11984
11985   return Result;
11986 }
11987
11988 SDValue
11989 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11990   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11991   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11992   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11993 }
11994
11995 static SDValue
11996 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11997            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11998            unsigned char OperandFlags, bool LocalDynamic = false) {
11999   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12000   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12001   SDLoc dl(GA);
12002   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12003                                            GA->getValueType(0),
12004                                            GA->getOffset(),
12005                                            OperandFlags);
12006
12007   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12008                                            : X86ISD::TLSADDR;
12009
12010   if (InFlag) {
12011     SDValue Ops[] = { Chain,  TGA, *InFlag };
12012     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12013   } else {
12014     SDValue Ops[]  = { Chain, TGA };
12015     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12016   }
12017
12018   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12019   MFI->setAdjustsStack(true);
12020   MFI->setHasCalls(true);
12021
12022   SDValue Flag = Chain.getValue(1);
12023   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12024 }
12025
12026 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12027 static SDValue
12028 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12029                                 const EVT PtrVT) {
12030   SDValue InFlag;
12031   SDLoc dl(GA);  // ? function entry point might be better
12032   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12033                                    DAG.getNode(X86ISD::GlobalBaseReg,
12034                                                SDLoc(), PtrVT), InFlag);
12035   InFlag = Chain.getValue(1);
12036
12037   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12038 }
12039
12040 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12041 static SDValue
12042 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12043                                 const EVT PtrVT) {
12044   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12045                     X86::RAX, X86II::MO_TLSGD);
12046 }
12047
12048 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12049                                            SelectionDAG &DAG,
12050                                            const EVT PtrVT,
12051                                            bool is64Bit) {
12052   SDLoc dl(GA);
12053
12054   // Get the start address of the TLS block for this module.
12055   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12056       .getInfo<X86MachineFunctionInfo>();
12057   MFI->incNumLocalDynamicTLSAccesses();
12058
12059   SDValue Base;
12060   if (is64Bit) {
12061     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12062                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12063   } else {
12064     SDValue InFlag;
12065     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12066         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12067     InFlag = Chain.getValue(1);
12068     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12069                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12070   }
12071
12072   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12073   // of Base.
12074
12075   // Build x@dtpoff.
12076   unsigned char OperandFlags = X86II::MO_DTPOFF;
12077   unsigned WrapperKind = X86ISD::Wrapper;
12078   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12079                                            GA->getValueType(0),
12080                                            GA->getOffset(), OperandFlags);
12081   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12082
12083   // Add x@dtpoff with the base.
12084   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12085 }
12086
12087 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12088 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12089                                    const EVT PtrVT, TLSModel::Model model,
12090                                    bool is64Bit, bool isPIC) {
12091   SDLoc dl(GA);
12092
12093   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12094   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12095                                                          is64Bit ? 257 : 256));
12096
12097   SDValue ThreadPointer =
12098       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12099                   MachinePointerInfo(Ptr), false, false, false, 0);
12100
12101   unsigned char OperandFlags = 0;
12102   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12103   // initialexec.
12104   unsigned WrapperKind = X86ISD::Wrapper;
12105   if (model == TLSModel::LocalExec) {
12106     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12107   } else if (model == TLSModel::InitialExec) {
12108     if (is64Bit) {
12109       OperandFlags = X86II::MO_GOTTPOFF;
12110       WrapperKind = X86ISD::WrapperRIP;
12111     } else {
12112       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12113     }
12114   } else {
12115     llvm_unreachable("Unexpected model");
12116   }
12117
12118   // emit "addl x@ntpoff,%eax" (local exec)
12119   // or "addl x@indntpoff,%eax" (initial exec)
12120   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12121   SDValue TGA =
12122       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12123                                  GA->getOffset(), OperandFlags);
12124   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12125
12126   if (model == TLSModel::InitialExec) {
12127     if (isPIC && !is64Bit) {
12128       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12129                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12130                            Offset);
12131     }
12132
12133     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12134                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12135                          false, false, false, 0);
12136   }
12137
12138   // The address of the thread local variable is the add of the thread
12139   // pointer with the offset of the variable.
12140   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12141 }
12142
12143 SDValue
12144 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12145
12146   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12147   const GlobalValue *GV = GA->getGlobal();
12148   auto PtrVT = getPointerTy(DAG.getDataLayout());
12149
12150   if (Subtarget->isTargetELF()) {
12151     if (DAG.getTarget().Options.EmulatedTLS)
12152       return LowerToTLSEmulatedModel(GA, DAG);
12153     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12154     switch (model) {
12155       case TLSModel::GeneralDynamic:
12156         if (Subtarget->is64Bit())
12157           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12158         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12159       case TLSModel::LocalDynamic:
12160         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12161                                            Subtarget->is64Bit());
12162       case TLSModel::InitialExec:
12163       case TLSModel::LocalExec:
12164         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12165                                    DAG.getTarget().getRelocationModel() ==
12166                                        Reloc::PIC_);
12167     }
12168     llvm_unreachable("Unknown TLS model.");
12169   }
12170
12171   if (Subtarget->isTargetDarwin()) {
12172     // Darwin only has one model of TLS.  Lower to that.
12173     unsigned char OpFlag = 0;
12174     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12175                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12176
12177     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12178     // global base reg.
12179     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12180                  !Subtarget->is64Bit();
12181     if (PIC32)
12182       OpFlag = X86II::MO_TLVP_PIC_BASE;
12183     else
12184       OpFlag = X86II::MO_TLVP;
12185     SDLoc DL(Op);
12186     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12187                                                 GA->getValueType(0),
12188                                                 GA->getOffset(), OpFlag);
12189     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12190
12191     // With PIC32, the address is actually $g + Offset.
12192     if (PIC32)
12193       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12194                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12195                            Offset);
12196
12197     // Lowering the machine isd will make sure everything is in the right
12198     // location.
12199     SDValue Chain = DAG.getEntryNode();
12200     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12201     SDValue Args[] = { Chain, Offset };
12202     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12203
12204     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12205     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12206     MFI->setAdjustsStack(true);
12207
12208     // And our return value (tls address) is in the standard call return value
12209     // location.
12210     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12211     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12212   }
12213
12214   if (Subtarget->isTargetKnownWindowsMSVC() ||
12215       Subtarget->isTargetWindowsGNU()) {
12216     // Just use the implicit TLS architecture
12217     // Need to generate someting similar to:
12218     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12219     //                                  ; from TEB
12220     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12221     //   mov     rcx, qword [rdx+rcx*8]
12222     //   mov     eax, .tls$:tlsvar
12223     //   [rax+rcx] contains the address
12224     // Windows 64bit: gs:0x58
12225     // Windows 32bit: fs:__tls_array
12226
12227     SDLoc dl(GA);
12228     SDValue Chain = DAG.getEntryNode();
12229
12230     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12231     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12232     // use its literal value of 0x2C.
12233     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12234                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12235                                                              256)
12236                                         : Type::getInt32PtrTy(*DAG.getContext(),
12237                                                               257));
12238
12239     SDValue TlsArray = Subtarget->is64Bit()
12240                            ? DAG.getIntPtrConstant(0x58, dl)
12241                            : (Subtarget->isTargetWindowsGNU()
12242                                   ? DAG.getIntPtrConstant(0x2C, dl)
12243                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12244
12245     SDValue ThreadPointer =
12246         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12247                     false, false, 0);
12248
12249     SDValue res;
12250     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12251       res = ThreadPointer;
12252     } else {
12253       // Load the _tls_index variable
12254       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12255       if (Subtarget->is64Bit())
12256         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12257                              MachinePointerInfo(), MVT::i32, false, false,
12258                              false, 0);
12259       else
12260         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12261                           false, false, 0);
12262
12263       auto &DL = DAG.getDataLayout();
12264       SDValue Scale =
12265           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12266       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12267
12268       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12269     }
12270
12271     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12272                       false, 0);
12273
12274     // Get the offset of start of .tls section
12275     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12276                                              GA->getValueType(0),
12277                                              GA->getOffset(), X86II::MO_SECREL);
12278     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12279
12280     // The address of the thread local variable is the add of the thread
12281     // pointer with the offset of the variable.
12282     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12283   }
12284
12285   llvm_unreachable("TLS not implemented for this target.");
12286 }
12287
12288 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12289 /// and take a 2 x i32 value to shift plus a shift amount.
12290 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12291   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12292   MVT VT = Op.getSimpleValueType();
12293   unsigned VTBits = VT.getSizeInBits();
12294   SDLoc dl(Op);
12295   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12296   SDValue ShOpLo = Op.getOperand(0);
12297   SDValue ShOpHi = Op.getOperand(1);
12298   SDValue ShAmt  = Op.getOperand(2);
12299   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12300   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12301   // during isel.
12302   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12303                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12304   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12305                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12306                        : DAG.getConstant(0, dl, VT);
12307
12308   SDValue Tmp2, Tmp3;
12309   if (Op.getOpcode() == ISD::SHL_PARTS) {
12310     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12311     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12312   } else {
12313     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12314     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12315   }
12316
12317   // If the shift amount is larger or equal than the width of a part we can't
12318   // rely on the results of shld/shrd. Insert a test and select the appropriate
12319   // values for large shift amounts.
12320   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12321                                 DAG.getConstant(VTBits, dl, MVT::i8));
12322   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12323                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12324
12325   SDValue Hi, Lo;
12326   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12327   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12328   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12329
12330   if (Op.getOpcode() == ISD::SHL_PARTS) {
12331     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12332     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12333   } else {
12334     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12335     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12336   }
12337
12338   SDValue Ops[2] = { Lo, Hi };
12339   return DAG.getMergeValues(Ops, dl);
12340 }
12341
12342 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12343                                            SelectionDAG &DAG) const {
12344   SDValue Src = Op.getOperand(0);
12345   MVT SrcVT = Src.getSimpleValueType();
12346   MVT VT = Op.getSimpleValueType();
12347   SDLoc dl(Op);
12348
12349   if (SrcVT.isVector()) {
12350     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12351       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12352                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12353                          DAG.getUNDEF(SrcVT)));
12354     }
12355     if (SrcVT.getVectorElementType() == MVT::i1) {
12356       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12357       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12358                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12359     }
12360     return SDValue();
12361   }
12362
12363   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12364          "Unknown SINT_TO_FP to lower!");
12365
12366   // These are really Legal; return the operand so the caller accepts it as
12367   // Legal.
12368   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12369     return Op;
12370   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12371       Subtarget->is64Bit()) {
12372     return Op;
12373   }
12374
12375   unsigned Size = SrcVT.getSizeInBits()/8;
12376   MachineFunction &MF = DAG.getMachineFunction();
12377   auto PtrVT = getPointerTy(MF.getDataLayout());
12378   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12379   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12380   SDValue Chain = DAG.getStore(
12381       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12382       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12383       false, 0);
12384   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12385 }
12386
12387 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12388                                      SDValue StackSlot,
12389                                      SelectionDAG &DAG) const {
12390   // Build the FILD
12391   SDLoc DL(Op);
12392   SDVTList Tys;
12393   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12394   if (useSSE)
12395     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12396   else
12397     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12398
12399   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12400
12401   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12402   MachineMemOperand *MMO;
12403   if (FI) {
12404     int SSFI = FI->getIndex();
12405     MMO = DAG.getMachineFunction().getMachineMemOperand(
12406         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12407         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12408   } else {
12409     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12410     StackSlot = StackSlot.getOperand(1);
12411   }
12412   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12413   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12414                                            X86ISD::FILD, DL,
12415                                            Tys, Ops, SrcVT, MMO);
12416
12417   if (useSSE) {
12418     Chain = Result.getValue(1);
12419     SDValue InFlag = Result.getValue(2);
12420
12421     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12422     // shouldn't be necessary except that RFP cannot be live across
12423     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12424     MachineFunction &MF = DAG.getMachineFunction();
12425     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12426     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12427     auto PtrVT = getPointerTy(MF.getDataLayout());
12428     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12429     Tys = DAG.getVTList(MVT::Other);
12430     SDValue Ops[] = {
12431       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12432     };
12433     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12434         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12435         MachineMemOperand::MOStore, SSFISize, SSFISize);
12436
12437     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12438                                     Ops, Op.getValueType(), MMO);
12439     Result = DAG.getLoad(
12440         Op.getValueType(), DL, Chain, StackSlot,
12441         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12442         false, false, false, 0);
12443   }
12444
12445   return Result;
12446 }
12447
12448 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12449 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12450                                                SelectionDAG &DAG) const {
12451   // This algorithm is not obvious. Here it is what we're trying to output:
12452   /*
12453      movq       %rax,  %xmm0
12454      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12455      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12456      #ifdef __SSE3__
12457        haddpd   %xmm0, %xmm0
12458      #else
12459        pshufd   $0x4e, %xmm0, %xmm1
12460        addpd    %xmm1, %xmm0
12461      #endif
12462   */
12463
12464   SDLoc dl(Op);
12465   LLVMContext *Context = DAG.getContext();
12466
12467   // Build some magic constants.
12468   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12469   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12470   auto PtrVT = getPointerTy(DAG.getDataLayout());
12471   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12472
12473   SmallVector<Constant*,2> CV1;
12474   CV1.push_back(
12475     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12476                                       APInt(64, 0x4330000000000000ULL))));
12477   CV1.push_back(
12478     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12479                                       APInt(64, 0x4530000000000000ULL))));
12480   Constant *C1 = ConstantVector::get(CV1);
12481   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12482
12483   // Load the 64-bit value into an XMM register.
12484   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12485                             Op.getOperand(0));
12486   SDValue CLod0 =
12487       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12488                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12489                   false, false, false, 16);
12490   SDValue Unpck1 =
12491       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12492
12493   SDValue CLod1 =
12494       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12495                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12496                   false, false, false, 16);
12497   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12498   // TODO: Are there any fast-math-flags to propagate here?
12499   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12500   SDValue Result;
12501
12502   if (Subtarget->hasSSE3()) {
12503     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12504     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12505   } else {
12506     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12507     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12508                                            S2F, 0x4E, DAG);
12509     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12510                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12511   }
12512
12513   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12514                      DAG.getIntPtrConstant(0, dl));
12515 }
12516
12517 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12518 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12519                                                SelectionDAG &DAG) const {
12520   SDLoc dl(Op);
12521   // FP constant to bias correct the final result.
12522   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12523                                    MVT::f64);
12524
12525   // Load the 32-bit value into an XMM register.
12526   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12527                              Op.getOperand(0));
12528
12529   // Zero out the upper parts of the register.
12530   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12531
12532   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12533                      DAG.getBitcast(MVT::v2f64, Load),
12534                      DAG.getIntPtrConstant(0, dl));
12535
12536   // Or the load with the bias.
12537   SDValue Or = DAG.getNode(
12538       ISD::OR, dl, MVT::v2i64,
12539       DAG.getBitcast(MVT::v2i64,
12540                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12541       DAG.getBitcast(MVT::v2i64,
12542                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12543   Or =
12544       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12545                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12546
12547   // Subtract the bias.
12548   // TODO: Are there any fast-math-flags to propagate here?
12549   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12550
12551   // Handle final rounding.
12552   MVT DestVT = Op.getSimpleValueType();
12553
12554   if (DestVT.bitsLT(MVT::f64))
12555     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12556                        DAG.getIntPtrConstant(0, dl));
12557   if (DestVT.bitsGT(MVT::f64))
12558     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12559
12560   // Handle final rounding.
12561   return Sub;
12562 }
12563
12564 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12565                                      const X86Subtarget &Subtarget) {
12566   // The algorithm is the following:
12567   // #ifdef __SSE4_1__
12568   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12569   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12570   //                                 (uint4) 0x53000000, 0xaa);
12571   // #else
12572   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12573   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12574   // #endif
12575   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12576   //     return (float4) lo + fhi;
12577
12578   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12579   // reassociate the two FADDs, and if we do that, the algorithm fails
12580   // spectacularly (PR24512).
12581   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12582   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12583   // there's also the MachineCombiner reassociations happening on Machine IR.
12584   if (DAG.getTarget().Options.UnsafeFPMath)
12585     return SDValue();
12586
12587   SDLoc DL(Op);
12588   SDValue V = Op->getOperand(0);
12589   MVT VecIntVT = V.getSimpleValueType();
12590   bool Is128 = VecIntVT == MVT::v4i32;
12591   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12592   // If we convert to something else than the supported type, e.g., to v4f64,
12593   // abort early.
12594   if (VecFloatVT != Op->getSimpleValueType(0))
12595     return SDValue();
12596
12597   unsigned NumElts = VecIntVT.getVectorNumElements();
12598   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12599          "Unsupported custom type");
12600   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12601
12602   // In the #idef/#else code, we have in common:
12603   // - The vector of constants:
12604   // -- 0x4b000000
12605   // -- 0x53000000
12606   // - A shift:
12607   // -- v >> 16
12608
12609   // Create the splat vector for 0x4b000000.
12610   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12611   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12612                            CstLow, CstLow, CstLow, CstLow};
12613   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12614                                   makeArrayRef(&CstLowArray[0], NumElts));
12615   // Create the splat vector for 0x53000000.
12616   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12617   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12618                             CstHigh, CstHigh, CstHigh, CstHigh};
12619   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12620                                    makeArrayRef(&CstHighArray[0], NumElts));
12621
12622   // Create the right shift.
12623   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12624   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12625                              CstShift, CstShift, CstShift, CstShift};
12626   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12627                                     makeArrayRef(&CstShiftArray[0], NumElts));
12628   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12629
12630   SDValue Low, High;
12631   if (Subtarget.hasSSE41()) {
12632     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12633     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12634     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12635     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12636     // Low will be bitcasted right away, so do not bother bitcasting back to its
12637     // original type.
12638     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12639                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12640     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12641     //                                 (uint4) 0x53000000, 0xaa);
12642     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12643     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12644     // High will be bitcasted right away, so do not bother bitcasting back to
12645     // its original type.
12646     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12647                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12648   } else {
12649     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12650     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12651                                      CstMask, CstMask, CstMask);
12652     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12653     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12654     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12655
12656     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12657     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12658   }
12659
12660   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12661   SDValue CstFAdd = DAG.getConstantFP(
12662       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12663   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12664                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12665   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12666                                    makeArrayRef(&CstFAddArray[0], NumElts));
12667
12668   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12669   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12670   // TODO: Are there any fast-math-flags to propagate here?
12671   SDValue FHigh =
12672       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12673   //     return (float4) lo + fhi;
12674   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12675   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12676 }
12677
12678 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12679                                                SelectionDAG &DAG) const {
12680   SDValue N0 = Op.getOperand(0);
12681   MVT SVT = N0.getSimpleValueType();
12682   SDLoc dl(Op);
12683
12684   switch (SVT.SimpleTy) {
12685   default:
12686     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12687   case MVT::v4i8:
12688   case MVT::v4i16:
12689   case MVT::v8i8:
12690   case MVT::v8i16: {
12691     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12692     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12693                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12694   }
12695   case MVT::v4i32:
12696   case MVT::v8i32:
12697     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12698   case MVT::v16i8:
12699   case MVT::v16i16:
12700     assert(Subtarget->hasAVX512());
12701     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12702                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12703   }
12704 }
12705
12706 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12707                                            SelectionDAG &DAG) const {
12708   SDValue N0 = Op.getOperand(0);
12709   SDLoc dl(Op);
12710   auto PtrVT = getPointerTy(DAG.getDataLayout());
12711
12712   if (Op.getSimpleValueType().isVector())
12713     return lowerUINT_TO_FP_vec(Op, DAG);
12714
12715   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12716   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12717   // the optimization here.
12718   if (DAG.SignBitIsZero(N0))
12719     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12720
12721   MVT SrcVT = N0.getSimpleValueType();
12722   MVT DstVT = Op.getSimpleValueType();
12723
12724   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12725       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12726     // Conversions from unsigned i32 to f32/f64 are legal,
12727     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12728     return Op;
12729   }
12730
12731   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12732     return LowerUINT_TO_FP_i64(Op, DAG);
12733   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12734     return LowerUINT_TO_FP_i32(Op, DAG);
12735   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12736     return SDValue();
12737
12738   // Make a 64-bit buffer, and use it to build an FILD.
12739   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12740   if (SrcVT == MVT::i32) {
12741     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12742     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12743     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12744                                   StackSlot, MachinePointerInfo(),
12745                                   false, false, 0);
12746     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12747                                   OffsetSlot, MachinePointerInfo(),
12748                                   false, false, 0);
12749     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12750     return Fild;
12751   }
12752
12753   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12754   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12755                                StackSlot, MachinePointerInfo(),
12756                                false, false, 0);
12757   // For i64 source, we need to add the appropriate power of 2 if the input
12758   // was negative.  This is the same as the optimization in
12759   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12760   // we must be careful to do the computation in x87 extended precision, not
12761   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12762   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12763   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12764       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12765       MachineMemOperand::MOLoad, 8, 8);
12766
12767   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12768   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12769   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12770                                          MVT::i64, MMO);
12771
12772   APInt FF(32, 0x5F800000ULL);
12773
12774   // Check whether the sign bit is set.
12775   SDValue SignSet = DAG.getSetCC(
12776       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12777       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12778
12779   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12780   SDValue FudgePtr = DAG.getConstantPool(
12781       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12782
12783   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12784   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12785   SDValue Four = DAG.getIntPtrConstant(4, dl);
12786   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12787                                Zero, Four);
12788   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12789
12790   // Load the value out, extending it from f32 to f80.
12791   // FIXME: Avoid the extend by constructing the right constant pool?
12792   SDValue Fudge = DAG.getExtLoad(
12793       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12794       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12795       false, false, false, 4);
12796   // Extend everything to 80 bits to force it to be done on x87.
12797   // TODO: Are there any fast-math-flags to propagate here?
12798   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12799   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12800                      DAG.getIntPtrConstant(0, dl));
12801 }
12802
12803 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12804 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12805 // just return an <SDValue(), SDValue()> pair.
12806 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12807 // to i16, i32 or i64, and we lower it to a legal sequence.
12808 // If lowered to the final integer result we return a <result, SDValue()> pair.
12809 // Otherwise we lower it to a sequence ending with a FIST, return a
12810 // <FIST, StackSlot> pair, and the caller is responsible for loading
12811 // the final integer result from StackSlot.
12812 std::pair<SDValue,SDValue>
12813 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12814                                    bool IsSigned, bool IsReplace) const {
12815   SDLoc DL(Op);
12816
12817   EVT DstTy = Op.getValueType();
12818   EVT TheVT = Op.getOperand(0).getValueType();
12819   auto PtrVT = getPointerTy(DAG.getDataLayout());
12820
12821   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12822     // f16 must be promoted before using the lowering in this routine.
12823     // fp128 does not use this lowering.
12824     return std::make_pair(SDValue(), SDValue());
12825   }
12826
12827   // If using FIST to compute an unsigned i64, we'll need some fixup
12828   // to handle values above the maximum signed i64.  A FIST is always
12829   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12830   bool UnsignedFixup = !IsSigned &&
12831                        DstTy == MVT::i64 &&
12832                        (!Subtarget->is64Bit() ||
12833                         !isScalarFPTypeInSSEReg(TheVT));
12834
12835   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12836     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12837     // The low 32 bits of the fist result will have the correct uint32 result.
12838     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12839     DstTy = MVT::i64;
12840   }
12841
12842   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12843          DstTy.getSimpleVT() >= MVT::i16 &&
12844          "Unknown FP_TO_INT to lower!");
12845
12846   // These are really Legal.
12847   if (DstTy == MVT::i32 &&
12848       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12849     return std::make_pair(SDValue(), SDValue());
12850   if (Subtarget->is64Bit() &&
12851       DstTy == MVT::i64 &&
12852       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12853     return std::make_pair(SDValue(), SDValue());
12854
12855   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12856   // stack slot.
12857   MachineFunction &MF = DAG.getMachineFunction();
12858   unsigned MemSize = DstTy.getSizeInBits()/8;
12859   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12860   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12861
12862   unsigned Opc;
12863   switch (DstTy.getSimpleVT().SimpleTy) {
12864   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12865   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12866   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12867   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12868   }
12869
12870   SDValue Chain = DAG.getEntryNode();
12871   SDValue Value = Op.getOperand(0);
12872   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12873
12874   if (UnsignedFixup) {
12875     //
12876     // Conversion to unsigned i64 is implemented with a select,
12877     // depending on whether the source value fits in the range
12878     // of a signed i64.  Let Thresh be the FP equivalent of
12879     // 0x8000000000000000ULL.
12880     //
12881     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12882     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12883     //  Fist-to-mem64 FistSrc
12884     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12885     //  to XOR'ing the high 32 bits with Adjust.
12886     //
12887     // Being a power of 2, Thresh is exactly representable in all FP formats.
12888     // For X87 we'd like to use the smallest FP type for this constant, but
12889     // for DAG type consistency we have to match the FP operand type.
12890
12891     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12892     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12893     bool LosesInfo = false;
12894     if (TheVT == MVT::f64)
12895       // The rounding mode is irrelevant as the conversion should be exact.
12896       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12897                               &LosesInfo);
12898     else if (TheVT == MVT::f80)
12899       Status = Thresh.convert(APFloat::x87DoubleExtended,
12900                               APFloat::rmNearestTiesToEven, &LosesInfo);
12901
12902     assert(Status == APFloat::opOK && !LosesInfo &&
12903            "FP conversion should have been exact");
12904
12905     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12906
12907     SDValue Cmp = DAG.getSetCC(DL,
12908                                getSetCCResultType(DAG.getDataLayout(),
12909                                                   *DAG.getContext(), TheVT),
12910                                Value, ThreshVal, ISD::SETLT);
12911     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12912                            DAG.getConstant(0, DL, MVT::i32),
12913                            DAG.getConstant(0x80000000, DL, MVT::i32));
12914     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12915     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12916                                               *DAG.getContext(), TheVT),
12917                        Value, ThreshVal, ISD::SETLT);
12918     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12919   }
12920
12921   // FIXME This causes a redundant load/store if the SSE-class value is already
12922   // in memory, such as if it is on the callstack.
12923   if (isScalarFPTypeInSSEReg(TheVT)) {
12924     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12925     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12926                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12927                          false, 0);
12928     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12929     SDValue Ops[] = {
12930       Chain, StackSlot, DAG.getValueType(TheVT)
12931     };
12932
12933     MachineMemOperand *MMO =
12934         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12935                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12936     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12937     Chain = Value.getValue(1);
12938     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12939     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12940   }
12941
12942   MachineMemOperand *MMO =
12943       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12944                               MachineMemOperand::MOStore, MemSize, MemSize);
12945
12946   if (UnsignedFixup) {
12947
12948     // Insert the FIST, load its result as two i32's,
12949     // and XOR the high i32 with Adjust.
12950
12951     SDValue FistOps[] = { Chain, Value, StackSlot };
12952     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12953                                            FistOps, DstTy, MMO);
12954
12955     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12956                                 MachinePointerInfo(),
12957                                 false, false, false, 0);
12958     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12959                                    DAG.getConstant(4, DL, PtrVT));
12960
12961     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12962                                  MachinePointerInfo(),
12963                                  false, false, false, 0);
12964     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12965
12966     if (Subtarget->is64Bit()) {
12967       // Join High32 and Low32 into a 64-bit result.
12968       // (High32 << 32) | Low32
12969       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12970       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12971       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12972                            DAG.getConstant(32, DL, MVT::i8));
12973       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12974       return std::make_pair(Result, SDValue());
12975     }
12976
12977     SDValue ResultOps[] = { Low32, High32 };
12978
12979     SDValue pair = IsReplace
12980       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12981       : DAG.getMergeValues(ResultOps, DL);
12982     return std::make_pair(pair, SDValue());
12983   } else {
12984     // Build the FP_TO_INT*_IN_MEM
12985     SDValue Ops[] = { Chain, Value, StackSlot };
12986     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12987                                            Ops, DstTy, MMO);
12988     return std::make_pair(FIST, StackSlot);
12989   }
12990 }
12991
12992 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12993                               const X86Subtarget *Subtarget) {
12994   MVT VT = Op->getSimpleValueType(0);
12995   SDValue In = Op->getOperand(0);
12996   MVT InVT = In.getSimpleValueType();
12997   SDLoc dl(Op);
12998
12999   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13000     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13001
13002   // Optimize vectors in AVX mode:
13003   //
13004   //   v8i16 -> v8i32
13005   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13006   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13007   //   Concat upper and lower parts.
13008   //
13009   //   v4i32 -> v4i64
13010   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13011   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13012   //   Concat upper and lower parts.
13013   //
13014
13015   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13016       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13017       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13018     return SDValue();
13019
13020   if (Subtarget->hasInt256())
13021     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13022
13023   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13024   SDValue Undef = DAG.getUNDEF(InVT);
13025   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13026   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13027   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13028
13029   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13030                              VT.getVectorNumElements()/2);
13031
13032   OpLo = DAG.getBitcast(HVT, OpLo);
13033   OpHi = DAG.getBitcast(HVT, OpHi);
13034
13035   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13036 }
13037
13038 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13039                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13040   MVT VT = Op->getSimpleValueType(0);
13041   SDValue In = Op->getOperand(0);
13042   MVT InVT = In.getSimpleValueType();
13043   SDLoc DL(Op);
13044   unsigned int NumElts = VT.getVectorNumElements();
13045   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13046     return SDValue();
13047
13048   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13049     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13050
13051   assert(InVT.getVectorElementType() == MVT::i1);
13052   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13053   SDValue One =
13054    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13055   SDValue Zero =
13056    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13057
13058   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13059   if (VT.is512BitVector())
13060     return V;
13061   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13062 }
13063
13064 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13065                                SelectionDAG &DAG) {
13066   if (Subtarget->hasFp256())
13067     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13068       return Res;
13069
13070   return SDValue();
13071 }
13072
13073 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13074                                 SelectionDAG &DAG) {
13075   SDLoc DL(Op);
13076   MVT VT = Op.getSimpleValueType();
13077   SDValue In = Op.getOperand(0);
13078   MVT SVT = In.getSimpleValueType();
13079
13080   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13081     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13082
13083   if (Subtarget->hasFp256())
13084     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13085       return Res;
13086
13087   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13088          VT.getVectorNumElements() != SVT.getVectorNumElements());
13089   return SDValue();
13090 }
13091
13092 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13093   SDLoc DL(Op);
13094   MVT VT = Op.getSimpleValueType();
13095   SDValue In = Op.getOperand(0);
13096   MVT InVT = In.getSimpleValueType();
13097
13098   if (VT == MVT::i1) {
13099     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13100            "Invalid scalar TRUNCATE operation");
13101     if (InVT.getSizeInBits() >= 32)
13102       return SDValue();
13103     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13104     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13105   }
13106   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13107          "Invalid TRUNCATE operation");
13108
13109   // move vector to mask - truncate solution for SKX
13110   if (VT.getVectorElementType() == MVT::i1) {
13111     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13112         Subtarget->hasBWI())
13113       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13114     if ((InVT.is256BitVector() || InVT.is128BitVector())
13115         && InVT.getScalarSizeInBits() <= 16 &&
13116         Subtarget->hasBWI() && Subtarget->hasVLX())
13117       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13118     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13119         Subtarget->hasDQI())
13120       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13121     if ((InVT.is256BitVector() || InVT.is128BitVector())
13122         && InVT.getScalarSizeInBits() >= 32 &&
13123         Subtarget->hasDQI() && Subtarget->hasVLX())
13124       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13125   }
13126
13127   if (VT.getVectorElementType() == MVT::i1) {
13128     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13129     unsigned NumElts = InVT.getVectorNumElements();
13130     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13131     if (InVT.getSizeInBits() < 512) {
13132       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13133       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13134       InVT = ExtVT;
13135     }
13136
13137     SDValue OneV =
13138      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13139     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13140     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13141   }
13142
13143   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13144   if (Subtarget->hasAVX512()) {
13145     // word to byte only under BWI
13146     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13147       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13148                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13149     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13150   }
13151   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13152     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13153     if (Subtarget->hasInt256()) {
13154       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13155       In = DAG.getBitcast(MVT::v8i32, In);
13156       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13157                                 ShufMask);
13158       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13159                          DAG.getIntPtrConstant(0, DL));
13160     }
13161
13162     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13163                                DAG.getIntPtrConstant(0, DL));
13164     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13165                                DAG.getIntPtrConstant(2, DL));
13166     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13167     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13168     static const int ShufMask[] = {0, 2, 4, 6};
13169     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13170   }
13171
13172   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13173     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13174     if (Subtarget->hasInt256()) {
13175       In = DAG.getBitcast(MVT::v32i8, In);
13176
13177       SmallVector<SDValue,32> pshufbMask;
13178       for (unsigned i = 0; i < 2; ++i) {
13179         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13180         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13181         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13182         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13183         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13184         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13185         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13186         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13187         for (unsigned j = 0; j < 8; ++j)
13188           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13189       }
13190       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13191       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13192       In = DAG.getBitcast(MVT::v4i64, In);
13193
13194       static const int ShufMask[] = {0,  2,  -1,  -1};
13195       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13196                                 &ShufMask[0]);
13197       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13198                        DAG.getIntPtrConstant(0, DL));
13199       return DAG.getBitcast(VT, In);
13200     }
13201
13202     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13203                                DAG.getIntPtrConstant(0, DL));
13204
13205     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13206                                DAG.getIntPtrConstant(4, DL));
13207
13208     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13209     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13210
13211     // The PSHUFB mask:
13212     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13213                                    -1, -1, -1, -1, -1, -1, -1, -1};
13214
13215     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13216     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13217     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13218
13219     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13220     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13221
13222     // The MOVLHPS Mask:
13223     static const int ShufMask2[] = {0, 1, 4, 5};
13224     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13225     return DAG.getBitcast(MVT::v8i16, res);
13226   }
13227
13228   // Handle truncation of V256 to V128 using shuffles.
13229   if (!VT.is128BitVector() || !InVT.is256BitVector())
13230     return SDValue();
13231
13232   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13233
13234   unsigned NumElems = VT.getVectorNumElements();
13235   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13236
13237   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13238   // Prepare truncation shuffle mask
13239   for (unsigned i = 0; i != NumElems; ++i)
13240     MaskVec[i] = i * 2;
13241   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13242                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13243   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13244                      DAG.getIntPtrConstant(0, DL));
13245 }
13246
13247 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13248                                            SelectionDAG &DAG) const {
13249   assert(!Op.getSimpleValueType().isVector());
13250
13251   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13252     /*IsSigned=*/ true, /*IsReplace=*/ false);
13253   SDValue FIST = Vals.first, StackSlot = Vals.second;
13254   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13255   if (!FIST.getNode())
13256     return Op;
13257
13258   if (StackSlot.getNode())
13259     // Load the result.
13260     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13261                        FIST, StackSlot, MachinePointerInfo(),
13262                        false, false, false, 0);
13263
13264   // The node is the result.
13265   return FIST;
13266 }
13267
13268 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13269                                            SelectionDAG &DAG) const {
13270   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13271     /*IsSigned=*/ false, /*IsReplace=*/ false);
13272   SDValue FIST = Vals.first, StackSlot = Vals.second;
13273   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13274   if (!FIST.getNode())
13275     return Op;
13276
13277   if (StackSlot.getNode())
13278     // Load the result.
13279     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13280                        FIST, StackSlot, MachinePointerInfo(),
13281                        false, false, false, 0);
13282
13283   // The node is the result.
13284   return FIST;
13285 }
13286
13287 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13288   SDLoc DL(Op);
13289   MVT VT = Op.getSimpleValueType();
13290   SDValue In = Op.getOperand(0);
13291   MVT SVT = In.getSimpleValueType();
13292
13293   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13294
13295   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13296                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13297                                  In, DAG.getUNDEF(SVT)));
13298 }
13299
13300 /// The only differences between FABS and FNEG are the mask and the logic op.
13301 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13302 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13303   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13304          "Wrong opcode for lowering FABS or FNEG.");
13305
13306   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13307
13308   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13309   // into an FNABS. We'll lower the FABS after that if it is still in use.
13310   if (IsFABS)
13311     for (SDNode *User : Op->uses())
13312       if (User->getOpcode() == ISD::FNEG)
13313         return Op;
13314
13315   SDLoc dl(Op);
13316   MVT VT = Op.getSimpleValueType();
13317
13318   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13319   // decide if we should generate a 16-byte constant mask when we only need 4 or
13320   // 8 bytes for the scalar case.
13321
13322   MVT LogicVT;
13323   MVT EltVT;
13324   unsigned NumElts;
13325
13326   if (VT.isVector()) {
13327     LogicVT = VT;
13328     EltVT = VT.getVectorElementType();
13329     NumElts = VT.getVectorNumElements();
13330   } else {
13331     // There are no scalar bitwise logical SSE/AVX instructions, so we
13332     // generate a 16-byte vector constant and logic op even for the scalar case.
13333     // Using a 16-byte mask allows folding the load of the mask with
13334     // the logic op, so it can save (~4 bytes) on code size.
13335     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13336     EltVT = VT;
13337     NumElts = (VT == MVT::f64) ? 2 : 4;
13338   }
13339
13340   unsigned EltBits = EltVT.getSizeInBits();
13341   LLVMContext *Context = DAG.getContext();
13342   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13343   APInt MaskElt =
13344     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13345   Constant *C = ConstantInt::get(*Context, MaskElt);
13346   C = ConstantVector::getSplat(NumElts, C);
13347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13348   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13349   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13350   SDValue Mask =
13351       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13352                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13353                   false, false, false, Alignment);
13354
13355   SDValue Op0 = Op.getOperand(0);
13356   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13357   unsigned LogicOp =
13358     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13359   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13360
13361   if (VT.isVector())
13362     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13363
13364   // For the scalar case extend to a 128-bit vector, perform the logic op,
13365   // and extract the scalar result back out.
13366   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13367   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13368   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13369                      DAG.getIntPtrConstant(0, dl));
13370 }
13371
13372 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13374   LLVMContext *Context = DAG.getContext();
13375   SDValue Op0 = Op.getOperand(0);
13376   SDValue Op1 = Op.getOperand(1);
13377   SDLoc dl(Op);
13378   MVT VT = Op.getSimpleValueType();
13379   MVT SrcVT = Op1.getSimpleValueType();
13380
13381   // If second operand is smaller, extend it first.
13382   if (SrcVT.bitsLT(VT)) {
13383     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13384     SrcVT = VT;
13385   }
13386   // And if it is bigger, shrink it first.
13387   if (SrcVT.bitsGT(VT)) {
13388     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13389     SrcVT = VT;
13390   }
13391
13392   // At this point the operands and the result should have the same
13393   // type, and that won't be f80 since that is not custom lowered.
13394
13395   const fltSemantics &Sem =
13396       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13397   const unsigned SizeInBits = VT.getSizeInBits();
13398
13399   SmallVector<Constant *, 4> CV(
13400       VT == MVT::f64 ? 2 : 4,
13401       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13402
13403   // First, clear all bits but the sign bit from the second operand (sign).
13404   CV[0] = ConstantFP::get(*Context,
13405                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13406   Constant *C = ConstantVector::get(CV);
13407   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13408   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13409
13410   // Perform all logic operations as 16-byte vectors because there are no
13411   // scalar FP logic instructions in SSE. This allows load folding of the
13412   // constants into the logic instructions.
13413   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13414   SDValue Mask1 =
13415       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13416                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13417                   false, false, false, 16);
13418   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13419   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13420
13421   // Next, clear the sign bit from the first operand (magnitude).
13422   // If it's a constant, we can clear it here.
13423   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13424     APFloat APF = Op0CN->getValueAPF();
13425     // If the magnitude is a positive zero, the sign bit alone is enough.
13426     if (APF.isPosZero())
13427       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13428                          DAG.getIntPtrConstant(0, dl));
13429     APF.clearSign();
13430     CV[0] = ConstantFP::get(*Context, APF);
13431   } else {
13432     CV[0] = ConstantFP::get(
13433         *Context,
13434         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13435   }
13436   C = ConstantVector::get(CV);
13437   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13438   SDValue Val =
13439       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13440                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13441                   false, false, false, 16);
13442   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13443   if (!isa<ConstantFPSDNode>(Op0)) {
13444     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13445     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13446   }
13447   // OR the magnitude value with the sign bit.
13448   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13449   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13450                      DAG.getIntPtrConstant(0, dl));
13451 }
13452
13453 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13454   SDValue N0 = Op.getOperand(0);
13455   SDLoc dl(Op);
13456   MVT VT = Op.getSimpleValueType();
13457
13458   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13459   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13460                                   DAG.getConstant(1, dl, VT));
13461   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13462 }
13463
13464 // Check whether an OR'd tree is PTEST-able.
13465 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13466                                       SelectionDAG &DAG) {
13467   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13468
13469   if (!Subtarget->hasSSE41())
13470     return SDValue();
13471
13472   if (!Op->hasOneUse())
13473     return SDValue();
13474
13475   SDNode *N = Op.getNode();
13476   SDLoc DL(N);
13477
13478   SmallVector<SDValue, 8> Opnds;
13479   DenseMap<SDValue, unsigned> VecInMap;
13480   SmallVector<SDValue, 8> VecIns;
13481   EVT VT = MVT::Other;
13482
13483   // Recognize a special case where a vector is casted into wide integer to
13484   // test all 0s.
13485   Opnds.push_back(N->getOperand(0));
13486   Opnds.push_back(N->getOperand(1));
13487
13488   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13489     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13490     // BFS traverse all OR'd operands.
13491     if (I->getOpcode() == ISD::OR) {
13492       Opnds.push_back(I->getOperand(0));
13493       Opnds.push_back(I->getOperand(1));
13494       // Re-evaluate the number of nodes to be traversed.
13495       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13496       continue;
13497     }
13498
13499     // Quit if a non-EXTRACT_VECTOR_ELT
13500     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13501       return SDValue();
13502
13503     // Quit if without a constant index.
13504     SDValue Idx = I->getOperand(1);
13505     if (!isa<ConstantSDNode>(Idx))
13506       return SDValue();
13507
13508     SDValue ExtractedFromVec = I->getOperand(0);
13509     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13510     if (M == VecInMap.end()) {
13511       VT = ExtractedFromVec.getValueType();
13512       // Quit if not 128/256-bit vector.
13513       if (!VT.is128BitVector() && !VT.is256BitVector())
13514         return SDValue();
13515       // Quit if not the same type.
13516       if (VecInMap.begin() != VecInMap.end() &&
13517           VT != VecInMap.begin()->first.getValueType())
13518         return SDValue();
13519       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13520       VecIns.push_back(ExtractedFromVec);
13521     }
13522     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13523   }
13524
13525   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13526          "Not extracted from 128-/256-bit vector.");
13527
13528   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13529
13530   for (DenseMap<SDValue, unsigned>::const_iterator
13531         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13532     // Quit if not all elements are used.
13533     if (I->second != FullMask)
13534       return SDValue();
13535   }
13536
13537   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13538
13539   // Cast all vectors into TestVT for PTEST.
13540   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13541     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13542
13543   // If more than one full vectors are evaluated, OR them first before PTEST.
13544   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13545     // Each iteration will OR 2 nodes and append the result until there is only
13546     // 1 node left, i.e. the final OR'd value of all vectors.
13547     SDValue LHS = VecIns[Slot];
13548     SDValue RHS = VecIns[Slot + 1];
13549     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13550   }
13551
13552   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13553                      VecIns.back(), VecIns.back());
13554 }
13555
13556 /// \brief return true if \c Op has a use that doesn't just read flags.
13557 static bool hasNonFlagsUse(SDValue Op) {
13558   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13559        ++UI) {
13560     SDNode *User = *UI;
13561     unsigned UOpNo = UI.getOperandNo();
13562     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13563       // Look pass truncate.
13564       UOpNo = User->use_begin().getOperandNo();
13565       User = *User->use_begin();
13566     }
13567
13568     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13569         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13570       return true;
13571   }
13572   return false;
13573 }
13574
13575 /// Emit nodes that will be selected as "test Op0,Op0", or something
13576 /// equivalent.
13577 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13578                                     SelectionDAG &DAG) const {
13579   if (Op.getValueType() == MVT::i1) {
13580     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13581     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13582                        DAG.getConstant(0, dl, MVT::i8));
13583   }
13584   // CF and OF aren't always set the way we want. Determine which
13585   // of these we need.
13586   bool NeedCF = false;
13587   bool NeedOF = false;
13588   switch (X86CC) {
13589   default: break;
13590   case X86::COND_A: case X86::COND_AE:
13591   case X86::COND_B: case X86::COND_BE:
13592     NeedCF = true;
13593     break;
13594   case X86::COND_G: case X86::COND_GE:
13595   case X86::COND_L: case X86::COND_LE:
13596   case X86::COND_O: case X86::COND_NO: {
13597     // Check if we really need to set the
13598     // Overflow flag. If NoSignedWrap is present
13599     // that is not actually needed.
13600     switch (Op->getOpcode()) {
13601     case ISD::ADD:
13602     case ISD::SUB:
13603     case ISD::MUL:
13604     case ISD::SHL: {
13605       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13606       if (BinNode->Flags.hasNoSignedWrap())
13607         break;
13608     }
13609     default:
13610       NeedOF = true;
13611       break;
13612     }
13613     break;
13614   }
13615   }
13616   // See if we can use the EFLAGS value from the operand instead of
13617   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13618   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13619   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13620     // Emit a CMP with 0, which is the TEST pattern.
13621     //if (Op.getValueType() == MVT::i1)
13622     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13623     //                     DAG.getConstant(0, MVT::i1));
13624     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13625                        DAG.getConstant(0, dl, Op.getValueType()));
13626   }
13627   unsigned Opcode = 0;
13628   unsigned NumOperands = 0;
13629
13630   // Truncate operations may prevent the merge of the SETCC instruction
13631   // and the arithmetic instruction before it. Attempt to truncate the operands
13632   // of the arithmetic instruction and use a reduced bit-width instruction.
13633   bool NeedTruncation = false;
13634   SDValue ArithOp = Op;
13635   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13636     SDValue Arith = Op->getOperand(0);
13637     // Both the trunc and the arithmetic op need to have one user each.
13638     if (Arith->hasOneUse())
13639       switch (Arith.getOpcode()) {
13640         default: break;
13641         case ISD::ADD:
13642         case ISD::SUB:
13643         case ISD::AND:
13644         case ISD::OR:
13645         case ISD::XOR: {
13646           NeedTruncation = true;
13647           ArithOp = Arith;
13648         }
13649       }
13650   }
13651
13652   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13653   // which may be the result of a CAST.  We use the variable 'Op', which is the
13654   // non-casted variable when we check for possible users.
13655   switch (ArithOp.getOpcode()) {
13656   case ISD::ADD:
13657     // Due to an isel shortcoming, be conservative if this add is likely to be
13658     // selected as part of a load-modify-store instruction. When the root node
13659     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13660     // uses of other nodes in the match, such as the ADD in this case. This
13661     // leads to the ADD being left around and reselected, with the result being
13662     // two adds in the output.  Alas, even if none our users are stores, that
13663     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13664     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13665     // climbing the DAG back to the root, and it doesn't seem to be worth the
13666     // effort.
13667     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13668          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13669       if (UI->getOpcode() != ISD::CopyToReg &&
13670           UI->getOpcode() != ISD::SETCC &&
13671           UI->getOpcode() != ISD::STORE)
13672         goto default_case;
13673
13674     if (ConstantSDNode *C =
13675         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13676       // An add of one will be selected as an INC.
13677       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13678         Opcode = X86ISD::INC;
13679         NumOperands = 1;
13680         break;
13681       }
13682
13683       // An add of negative one (subtract of one) will be selected as a DEC.
13684       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13685         Opcode = X86ISD::DEC;
13686         NumOperands = 1;
13687         break;
13688       }
13689     }
13690
13691     // Otherwise use a regular EFLAGS-setting add.
13692     Opcode = X86ISD::ADD;
13693     NumOperands = 2;
13694     break;
13695   case ISD::SHL:
13696   case ISD::SRL:
13697     // If we have a constant logical shift that's only used in a comparison
13698     // against zero turn it into an equivalent AND. This allows turning it into
13699     // a TEST instruction later.
13700     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13701         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13702       EVT VT = Op.getValueType();
13703       unsigned BitWidth = VT.getSizeInBits();
13704       unsigned ShAmt = Op->getConstantOperandVal(1);
13705       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13706         break;
13707       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13708                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13709                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13710       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13711         break;
13712       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13713                                 DAG.getConstant(Mask, dl, VT));
13714       DAG.ReplaceAllUsesWith(Op, New);
13715       Op = New;
13716     }
13717     break;
13718
13719   case ISD::AND:
13720     // If the primary and result isn't used, don't bother using X86ISD::AND,
13721     // because a TEST instruction will be better.
13722     if (!hasNonFlagsUse(Op))
13723       break;
13724     // FALL THROUGH
13725   case ISD::SUB:
13726   case ISD::OR:
13727   case ISD::XOR:
13728     // Due to the ISEL shortcoming noted above, be conservative if this op is
13729     // likely to be selected as part of a load-modify-store instruction.
13730     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13731            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13732       if (UI->getOpcode() == ISD::STORE)
13733         goto default_case;
13734
13735     // Otherwise use a regular EFLAGS-setting instruction.
13736     switch (ArithOp.getOpcode()) {
13737     default: llvm_unreachable("unexpected operator!");
13738     case ISD::SUB: Opcode = X86ISD::SUB; break;
13739     case ISD::XOR: Opcode = X86ISD::XOR; break;
13740     case ISD::AND: Opcode = X86ISD::AND; break;
13741     case ISD::OR: {
13742       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13743         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13744         if (EFLAGS.getNode())
13745           return EFLAGS;
13746       }
13747       Opcode = X86ISD::OR;
13748       break;
13749     }
13750     }
13751
13752     NumOperands = 2;
13753     break;
13754   case X86ISD::ADD:
13755   case X86ISD::SUB:
13756   case X86ISD::INC:
13757   case X86ISD::DEC:
13758   case X86ISD::OR:
13759   case X86ISD::XOR:
13760   case X86ISD::AND:
13761     return SDValue(Op.getNode(), 1);
13762   default:
13763   default_case:
13764     break;
13765   }
13766
13767   // If we found that truncation is beneficial, perform the truncation and
13768   // update 'Op'.
13769   if (NeedTruncation) {
13770     EVT VT = Op.getValueType();
13771     SDValue WideVal = Op->getOperand(0);
13772     EVT WideVT = WideVal.getValueType();
13773     unsigned ConvertedOp = 0;
13774     // Use a target machine opcode to prevent further DAGCombine
13775     // optimizations that may separate the arithmetic operations
13776     // from the setcc node.
13777     switch (WideVal.getOpcode()) {
13778       default: break;
13779       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13780       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13781       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13782       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13783       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13784     }
13785
13786     if (ConvertedOp) {
13787       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13788       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13789         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13790         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13791         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13792       }
13793     }
13794   }
13795
13796   if (Opcode == 0)
13797     // Emit a CMP with 0, which is the TEST pattern.
13798     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13799                        DAG.getConstant(0, dl, Op.getValueType()));
13800
13801   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13802   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13803
13804   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13805   DAG.ReplaceAllUsesWith(Op, New);
13806   return SDValue(New.getNode(), 1);
13807 }
13808
13809 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13810 /// equivalent.
13811 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13812                                    SDLoc dl, SelectionDAG &DAG) const {
13813   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13814     if (C->getAPIntValue() == 0)
13815       return EmitTest(Op0, X86CC, dl, DAG);
13816
13817      assert(Op0.getValueType() != MVT::i1 &&
13818             "Unexpected comparison operation for MVT::i1 operands");
13819   }
13820
13821   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13822        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13823     // Do the comparison at i32 if it's smaller, besides the Atom case.
13824     // This avoids subregister aliasing issues. Keep the smaller reference
13825     // if we're optimizing for size, however, as that'll allow better folding
13826     // of memory operations.
13827     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13828         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13829         !Subtarget->isAtom()) {
13830       unsigned ExtendOp =
13831           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13832       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13833       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13834     }
13835     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13836     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13837     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13838                               Op0, Op1);
13839     return SDValue(Sub.getNode(), 1);
13840   }
13841   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13842 }
13843
13844 /// Convert a comparison if required by the subtarget.
13845 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13846                                                  SelectionDAG &DAG) const {
13847   // If the subtarget does not support the FUCOMI instruction, floating-point
13848   // comparisons have to be converted.
13849   if (Subtarget->hasCMov() ||
13850       Cmp.getOpcode() != X86ISD::CMP ||
13851       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13852       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13853     return Cmp;
13854
13855   // The instruction selector will select an FUCOM instruction instead of
13856   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13857   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13858   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13859   SDLoc dl(Cmp);
13860   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13861   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13862   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13863                             DAG.getConstant(8, dl, MVT::i8));
13864   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13865   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13866 }
13867
13868 /// The minimum architected relative accuracy is 2^-12. We need one
13869 /// Newton-Raphson step to have a good float result (24 bits of precision).
13870 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13871                                             DAGCombinerInfo &DCI,
13872                                             unsigned &RefinementSteps,
13873                                             bool &UseOneConstNR) const {
13874   EVT VT = Op.getValueType();
13875   const char *RecipOp;
13876
13877   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13878   // TODO: Add support for AVX512 (v16f32).
13879   // It is likely not profitable to do this for f64 because a double-precision
13880   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13881   // instructions: convert to single, rsqrtss, convert back to double, refine
13882   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13883   // along with FMA, this could be a throughput win.
13884   if (VT == MVT::f32 && Subtarget->hasSSE1())
13885     RecipOp = "sqrtf";
13886   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13887            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13888     RecipOp = "vec-sqrtf";
13889   else
13890     return SDValue();
13891
13892   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13893   if (!Recips.isEnabled(RecipOp))
13894     return SDValue();
13895
13896   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13897   UseOneConstNR = false;
13898   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13899 }
13900
13901 /// The minimum architected relative accuracy is 2^-12. We need one
13902 /// Newton-Raphson step to have a good float result (24 bits of precision).
13903 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13904                                             DAGCombinerInfo &DCI,
13905                                             unsigned &RefinementSteps) const {
13906   EVT VT = Op.getValueType();
13907   const char *RecipOp;
13908
13909   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13910   // TODO: Add support for AVX512 (v16f32).
13911   // It is likely not profitable to do this for f64 because a double-precision
13912   // reciprocal estimate with refinement on x86 prior to FMA requires
13913   // 15 instructions: convert to single, rcpss, convert back to double, refine
13914   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13915   // along with FMA, this could be a throughput win.
13916   if (VT == MVT::f32 && Subtarget->hasSSE1())
13917     RecipOp = "divf";
13918   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13919            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13920     RecipOp = "vec-divf";
13921   else
13922     return SDValue();
13923
13924   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13925   if (!Recips.isEnabled(RecipOp))
13926     return SDValue();
13927
13928   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13929   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13930 }
13931
13932 /// If we have at least two divisions that use the same divisor, convert to
13933 /// multplication by a reciprocal. This may need to be adjusted for a given
13934 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13935 /// This is because we still need one division to calculate the reciprocal and
13936 /// then we need two multiplies by that reciprocal as replacements for the
13937 /// original divisions.
13938 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13939   return 2;
13940 }
13941
13942 static bool isAllOnes(SDValue V) {
13943   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13944   return C && C->isAllOnesValue();
13945 }
13946
13947 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13948 /// if it's possible.
13949 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13950                                      SDLoc dl, SelectionDAG &DAG) const {
13951   SDValue Op0 = And.getOperand(0);
13952   SDValue Op1 = And.getOperand(1);
13953   if (Op0.getOpcode() == ISD::TRUNCATE)
13954     Op0 = Op0.getOperand(0);
13955   if (Op1.getOpcode() == ISD::TRUNCATE)
13956     Op1 = Op1.getOperand(0);
13957
13958   SDValue LHS, RHS;
13959   if (Op1.getOpcode() == ISD::SHL)
13960     std::swap(Op0, Op1);
13961   if (Op0.getOpcode() == ISD::SHL) {
13962     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13963       if (And00C->getZExtValue() == 1) {
13964         // If we looked past a truncate, check that it's only truncating away
13965         // known zeros.
13966         unsigned BitWidth = Op0.getValueSizeInBits();
13967         unsigned AndBitWidth = And.getValueSizeInBits();
13968         if (BitWidth > AndBitWidth) {
13969           APInt Zeros, Ones;
13970           DAG.computeKnownBits(Op0, Zeros, Ones);
13971           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13972             return SDValue();
13973         }
13974         LHS = Op1;
13975         RHS = Op0.getOperand(1);
13976       }
13977   } else if (Op1.getOpcode() == ISD::Constant) {
13978     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13979     uint64_t AndRHSVal = AndRHS->getZExtValue();
13980     SDValue AndLHS = Op0;
13981
13982     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13983       LHS = AndLHS.getOperand(0);
13984       RHS = AndLHS.getOperand(1);
13985     }
13986
13987     // Use BT if the immediate can't be encoded in a TEST instruction.
13988     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13989       LHS = AndLHS;
13990       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13991     }
13992   }
13993
13994   if (LHS.getNode()) {
13995     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13996     // instruction.  Since the shift amount is in-range-or-undefined, we know
13997     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13998     // the encoding for the i16 version is larger than the i32 version.
13999     // Also promote i16 to i32 for performance / code size reason.
14000     if (LHS.getValueType() == MVT::i8 ||
14001         LHS.getValueType() == MVT::i16)
14002       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14003
14004     // If the operand types disagree, extend the shift amount to match.  Since
14005     // BT ignores high bits (like shifts) we can use anyextend.
14006     if (LHS.getValueType() != RHS.getValueType())
14007       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14008
14009     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14010     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14011     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14012                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14013   }
14014
14015   return SDValue();
14016 }
14017
14018 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14019 /// mask CMPs.
14020 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14021                               SDValue &Op1) {
14022   unsigned SSECC;
14023   bool Swap = false;
14024
14025   // SSE Condition code mapping:
14026   //  0 - EQ
14027   //  1 - LT
14028   //  2 - LE
14029   //  3 - UNORD
14030   //  4 - NEQ
14031   //  5 - NLT
14032   //  6 - NLE
14033   //  7 - ORD
14034   switch (SetCCOpcode) {
14035   default: llvm_unreachable("Unexpected SETCC condition");
14036   case ISD::SETOEQ:
14037   case ISD::SETEQ:  SSECC = 0; break;
14038   case ISD::SETOGT:
14039   case ISD::SETGT:  Swap = true; // Fallthrough
14040   case ISD::SETLT:
14041   case ISD::SETOLT: SSECC = 1; break;
14042   case ISD::SETOGE:
14043   case ISD::SETGE:  Swap = true; // Fallthrough
14044   case ISD::SETLE:
14045   case ISD::SETOLE: SSECC = 2; break;
14046   case ISD::SETUO:  SSECC = 3; break;
14047   case ISD::SETUNE:
14048   case ISD::SETNE:  SSECC = 4; break;
14049   case ISD::SETULE: Swap = true; // Fallthrough
14050   case ISD::SETUGE: SSECC = 5; break;
14051   case ISD::SETULT: Swap = true; // Fallthrough
14052   case ISD::SETUGT: SSECC = 6; break;
14053   case ISD::SETO:   SSECC = 7; break;
14054   case ISD::SETUEQ:
14055   case ISD::SETONE: SSECC = 8; break;
14056   }
14057   if (Swap)
14058     std::swap(Op0, Op1);
14059
14060   return SSECC;
14061 }
14062
14063 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14064 // ones, and then concatenate the result back.
14065 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14066   MVT VT = Op.getSimpleValueType();
14067
14068   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14069          "Unsupported value type for operation");
14070
14071   unsigned NumElems = VT.getVectorNumElements();
14072   SDLoc dl(Op);
14073   SDValue CC = Op.getOperand(2);
14074
14075   // Extract the LHS vectors
14076   SDValue LHS = Op.getOperand(0);
14077   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14078   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14079
14080   // Extract the RHS vectors
14081   SDValue RHS = Op.getOperand(1);
14082   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14083   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14084
14085   // Issue the operation on the smaller types and concatenate the result back
14086   MVT EltVT = VT.getVectorElementType();
14087   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14088   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14089                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14090                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14091 }
14092
14093 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14094   SDValue Op0 = Op.getOperand(0);
14095   SDValue Op1 = Op.getOperand(1);
14096   SDValue CC = Op.getOperand(2);
14097   MVT VT = Op.getSimpleValueType();
14098   SDLoc dl(Op);
14099
14100   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14101          "Unexpected type for boolean compare operation");
14102   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14103   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14104                                DAG.getConstant(-1, dl, VT));
14105   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14106                                DAG.getConstant(-1, dl, VT));
14107   switch (SetCCOpcode) {
14108   default: llvm_unreachable("Unexpected SETCC condition");
14109   case ISD::SETEQ:
14110     // (x == y) -> ~(x ^ y)
14111     return DAG.getNode(ISD::XOR, dl, VT,
14112                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14113                        DAG.getConstant(-1, dl, VT));
14114   case ISD::SETNE:
14115     // (x != y) -> (x ^ y)
14116     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14117   case ISD::SETUGT:
14118   case ISD::SETGT:
14119     // (x > y) -> (x & ~y)
14120     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14121   case ISD::SETULT:
14122   case ISD::SETLT:
14123     // (x < y) -> (~x & y)
14124     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14125   case ISD::SETULE:
14126   case ISD::SETLE:
14127     // (x <= y) -> (~x | y)
14128     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14129   case ISD::SETUGE:
14130   case ISD::SETGE:
14131     // (x >=y) -> (x | ~y)
14132     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14133   }
14134 }
14135
14136 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14137                                      const X86Subtarget *Subtarget) {
14138   SDValue Op0 = Op.getOperand(0);
14139   SDValue Op1 = Op.getOperand(1);
14140   SDValue CC = Op.getOperand(2);
14141   MVT VT = Op.getSimpleValueType();
14142   SDLoc dl(Op);
14143
14144   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14145          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14146          "Cannot set masked compare for this operation");
14147
14148   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14149   unsigned  Opc = 0;
14150   bool Unsigned = false;
14151   bool Swap = false;
14152   unsigned SSECC;
14153   switch (SetCCOpcode) {
14154   default: llvm_unreachable("Unexpected SETCC condition");
14155   case ISD::SETNE:  SSECC = 4; break;
14156   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14157   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14158   case ISD::SETLT:  Swap = true; //fall-through
14159   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14160   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14161   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14162   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14163   case ISD::SETULE: Unsigned = true; //fall-through
14164   case ISD::SETLE:  SSECC = 2; break;
14165   }
14166
14167   if (Swap)
14168     std::swap(Op0, Op1);
14169   if (Opc)
14170     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14171   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14172   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14173                      DAG.getConstant(SSECC, dl, MVT::i8));
14174 }
14175
14176 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14177 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14178 /// return an empty value.
14179 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14180 {
14181   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14182   if (!BV)
14183     return SDValue();
14184
14185   MVT VT = Op1.getSimpleValueType();
14186   MVT EVT = VT.getVectorElementType();
14187   unsigned n = VT.getVectorNumElements();
14188   SmallVector<SDValue, 8> ULTOp1;
14189
14190   for (unsigned i = 0; i < n; ++i) {
14191     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14192     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14193       return SDValue();
14194
14195     // Avoid underflow.
14196     APInt Val = Elt->getAPIntValue();
14197     if (Val == 0)
14198       return SDValue();
14199
14200     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14201   }
14202
14203   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14204 }
14205
14206 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14207                            SelectionDAG &DAG) {
14208   SDValue Op0 = Op.getOperand(0);
14209   SDValue Op1 = Op.getOperand(1);
14210   SDValue CC = Op.getOperand(2);
14211   MVT VT = Op.getSimpleValueType();
14212   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14213   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14214   SDLoc dl(Op);
14215
14216   if (isFP) {
14217 #ifndef NDEBUG
14218     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14219     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14220 #endif
14221
14222     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14223     unsigned Opc = X86ISD::CMPP;
14224     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14225       assert(VT.getVectorNumElements() <= 16);
14226       Opc = X86ISD::CMPM;
14227     }
14228     // In the two special cases we can't handle, emit two comparisons.
14229     if (SSECC == 8) {
14230       unsigned CC0, CC1;
14231       unsigned CombineOpc;
14232       if (SetCCOpcode == ISD::SETUEQ) {
14233         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14234       } else {
14235         assert(SetCCOpcode == ISD::SETONE);
14236         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14237       }
14238
14239       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14240                                  DAG.getConstant(CC0, dl, MVT::i8));
14241       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14242                                  DAG.getConstant(CC1, dl, MVT::i8));
14243       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14244     }
14245     // Handle all other FP comparisons here.
14246     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14247                        DAG.getConstant(SSECC, dl, MVT::i8));
14248   }
14249
14250   MVT VTOp0 = Op0.getSimpleValueType();
14251   assert(VTOp0 == Op1.getSimpleValueType() &&
14252          "Expected operands with same type!");
14253   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14254          "Invalid number of packed elements for source and destination!");
14255
14256   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14257     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14258     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14259     // legalizer firstly checks if the first operand in input to the setcc has
14260     // a legal type. If so, then it promotes the return type to that same type.
14261     // Otherwise, the return type is promoted to the 'next legal type' which,
14262     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14263     //
14264     // We reach this code only if the following two conditions are met:
14265     // 1. Both return type and operand type have been promoted to wider types
14266     //    by the type legalizer.
14267     // 2. The original operand type has been promoted to a 256-bit vector.
14268     //
14269     // Note that condition 2. only applies for AVX targets.
14270     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14271     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14272   }
14273
14274   // The non-AVX512 code below works under the assumption that source and
14275   // destination types are the same.
14276   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14277          "Value types for source and destination must be the same!");
14278
14279   // Break 256-bit integer vector compare into smaller ones.
14280   if (VT.is256BitVector() && !Subtarget->hasInt256())
14281     return Lower256IntVSETCC(Op, DAG);
14282
14283   MVT OpVT = Op1.getSimpleValueType();
14284   if (OpVT.getVectorElementType() == MVT::i1)
14285     return LowerBoolVSETCC_AVX512(Op, DAG);
14286
14287   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14288   if (Subtarget->hasAVX512()) {
14289     if (Op1.getSimpleValueType().is512BitVector() ||
14290         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14291         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14292       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14293
14294     // In AVX-512 architecture setcc returns mask with i1 elements,
14295     // But there is no compare instruction for i8 and i16 elements in KNL.
14296     // We are not talking about 512-bit operands in this case, these
14297     // types are illegal.
14298     if (MaskResult &&
14299         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14300          OpVT.getVectorElementType().getSizeInBits() >= 8))
14301       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14302                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14303   }
14304
14305   // Lower using XOP integer comparisons.
14306   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14307        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14308     // Translate compare code to XOP PCOM compare mode.
14309     unsigned CmpMode = 0;
14310     switch (SetCCOpcode) {
14311     default: llvm_unreachable("Unexpected SETCC condition");
14312     case ISD::SETULT:
14313     case ISD::SETLT: CmpMode = 0x00; break;
14314     case ISD::SETULE:
14315     case ISD::SETLE: CmpMode = 0x01; break;
14316     case ISD::SETUGT:
14317     case ISD::SETGT: CmpMode = 0x02; break;
14318     case ISD::SETUGE:
14319     case ISD::SETGE: CmpMode = 0x03; break;
14320     case ISD::SETEQ: CmpMode = 0x04; break;
14321     case ISD::SETNE: CmpMode = 0x05; break;
14322     }
14323
14324     // Are we comparing unsigned or signed integers?
14325     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14326       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14327
14328     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14329                        DAG.getConstant(CmpMode, dl, MVT::i8));
14330   }
14331
14332   // We are handling one of the integer comparisons here.  Since SSE only has
14333   // GT and EQ comparisons for integer, swapping operands and multiple
14334   // operations may be required for some comparisons.
14335   unsigned Opc;
14336   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14337   bool Subus = false;
14338
14339   switch (SetCCOpcode) {
14340   default: llvm_unreachable("Unexpected SETCC condition");
14341   case ISD::SETNE:  Invert = true;
14342   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14343   case ISD::SETLT:  Swap = true;
14344   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14345   case ISD::SETGE:  Swap = true;
14346   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14347                     Invert = true; break;
14348   case ISD::SETULT: Swap = true;
14349   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14350                     FlipSigns = true; break;
14351   case ISD::SETUGE: Swap = true;
14352   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14353                     FlipSigns = true; Invert = true; break;
14354   }
14355
14356   // Special case: Use min/max operations for SETULE/SETUGE
14357   MVT VET = VT.getVectorElementType();
14358   bool hasMinMax =
14359        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14360     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14361
14362   if (hasMinMax) {
14363     switch (SetCCOpcode) {
14364     default: break;
14365     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14366     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14367     }
14368
14369     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14370   }
14371
14372   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14373   if (!MinMax && hasSubus) {
14374     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14375     // Op0 u<= Op1:
14376     //   t = psubus Op0, Op1
14377     //   pcmpeq t, <0..0>
14378     switch (SetCCOpcode) {
14379     default: break;
14380     case ISD::SETULT: {
14381       // If the comparison is against a constant we can turn this into a
14382       // setule.  With psubus, setule does not require a swap.  This is
14383       // beneficial because the constant in the register is no longer
14384       // destructed as the destination so it can be hoisted out of a loop.
14385       // Only do this pre-AVX since vpcmp* is no longer destructive.
14386       if (Subtarget->hasAVX())
14387         break;
14388       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14389       if (ULEOp1.getNode()) {
14390         Op1 = ULEOp1;
14391         Subus = true; Invert = false; Swap = false;
14392       }
14393       break;
14394     }
14395     // Psubus is better than flip-sign because it requires no inversion.
14396     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14397     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14398     }
14399
14400     if (Subus) {
14401       Opc = X86ISD::SUBUS;
14402       FlipSigns = false;
14403     }
14404   }
14405
14406   if (Swap)
14407     std::swap(Op0, Op1);
14408
14409   // Check that the operation in question is available (most are plain SSE2,
14410   // but PCMPGTQ and PCMPEQQ have different requirements).
14411   if (VT == MVT::v2i64) {
14412     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14413       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14414
14415       // First cast everything to the right type.
14416       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14417       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14418
14419       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14420       // bits of the inputs before performing those operations. The lower
14421       // compare is always unsigned.
14422       SDValue SB;
14423       if (FlipSigns) {
14424         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14425       } else {
14426         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14427         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14428         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14429                          Sign, Zero, Sign, Zero);
14430       }
14431       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14432       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14433
14434       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14435       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14436       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14437
14438       // Create masks for only the low parts/high parts of the 64 bit integers.
14439       static const int MaskHi[] = { 1, 1, 3, 3 };
14440       static const int MaskLo[] = { 0, 0, 2, 2 };
14441       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14442       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14443       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14444
14445       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14446       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14447
14448       if (Invert)
14449         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14450
14451       return DAG.getBitcast(VT, Result);
14452     }
14453
14454     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14455       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14456       // pcmpeqd + pshufd + pand.
14457       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14458
14459       // First cast everything to the right type.
14460       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14461       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14462
14463       // Do the compare.
14464       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14465
14466       // Make sure the lower and upper halves are both all-ones.
14467       static const int Mask[] = { 1, 0, 3, 2 };
14468       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14469       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14470
14471       if (Invert)
14472         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14473
14474       return DAG.getBitcast(VT, Result);
14475     }
14476   }
14477
14478   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14479   // bits of the inputs before performing those operations.
14480   if (FlipSigns) {
14481     MVT EltVT = VT.getVectorElementType();
14482     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14483                                  VT);
14484     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14485     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14486   }
14487
14488   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14489
14490   // If the logical-not of the result is required, perform that now.
14491   if (Invert)
14492     Result = DAG.getNOT(dl, Result, VT);
14493
14494   if (MinMax)
14495     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14496
14497   if (Subus)
14498     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14499                          getZeroVector(VT, Subtarget, DAG, dl));
14500
14501   return Result;
14502 }
14503
14504 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14505
14506   MVT VT = Op.getSimpleValueType();
14507
14508   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14509
14510   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14511          && "SetCC type must be 8-bit or 1-bit integer");
14512   SDValue Op0 = Op.getOperand(0);
14513   SDValue Op1 = Op.getOperand(1);
14514   SDLoc dl(Op);
14515   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14516
14517   // Optimize to BT if possible.
14518   // Lower (X & (1 << N)) == 0 to BT(X, N).
14519   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14520   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14521   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14522       Op1.getOpcode() == ISD::Constant &&
14523       cast<ConstantSDNode>(Op1)->isNullValue() &&
14524       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14525     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14526       if (VT == MVT::i1)
14527         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14528       return NewSetCC;
14529     }
14530   }
14531
14532   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14533   // these.
14534   if (Op1.getOpcode() == ISD::Constant &&
14535       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14536        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14537       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14538
14539     // If the input is a setcc, then reuse the input setcc or use a new one with
14540     // the inverted condition.
14541     if (Op0.getOpcode() == X86ISD::SETCC) {
14542       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14543       bool Invert = (CC == ISD::SETNE) ^
14544         cast<ConstantSDNode>(Op1)->isNullValue();
14545       if (!Invert)
14546         return Op0;
14547
14548       CCode = X86::GetOppositeBranchCondition(CCode);
14549       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14550                                   DAG.getConstant(CCode, dl, MVT::i8),
14551                                   Op0.getOperand(1));
14552       if (VT == MVT::i1)
14553         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14554       return SetCC;
14555     }
14556   }
14557   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14558       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14559       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14560
14561     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14562     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14563   }
14564
14565   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14566   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14567   if (X86CC == X86::COND_INVALID)
14568     return SDValue();
14569
14570   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14571   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14572   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14573                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14574   if (VT == MVT::i1)
14575     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14576   return SetCC;
14577 }
14578
14579 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14580 static bool isX86LogicalCmp(SDValue Op) {
14581   unsigned Opc = Op.getNode()->getOpcode();
14582   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14583       Opc == X86ISD::SAHF)
14584     return true;
14585   if (Op.getResNo() == 1 &&
14586       (Opc == X86ISD::ADD ||
14587        Opc == X86ISD::SUB ||
14588        Opc == X86ISD::ADC ||
14589        Opc == X86ISD::SBB ||
14590        Opc == X86ISD::SMUL ||
14591        Opc == X86ISD::UMUL ||
14592        Opc == X86ISD::INC ||
14593        Opc == X86ISD::DEC ||
14594        Opc == X86ISD::OR ||
14595        Opc == X86ISD::XOR ||
14596        Opc == X86ISD::AND))
14597     return true;
14598
14599   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14600     return true;
14601
14602   return false;
14603 }
14604
14605 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14606   if (V.getOpcode() != ISD::TRUNCATE)
14607     return false;
14608
14609   SDValue VOp0 = V.getOperand(0);
14610   unsigned InBits = VOp0.getValueSizeInBits();
14611   unsigned Bits = V.getValueSizeInBits();
14612   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14613 }
14614
14615 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14616   bool addTest = true;
14617   SDValue Cond  = Op.getOperand(0);
14618   SDValue Op1 = Op.getOperand(1);
14619   SDValue Op2 = Op.getOperand(2);
14620   SDLoc DL(Op);
14621   MVT VT = Op1.getSimpleValueType();
14622   SDValue CC;
14623
14624   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14625   // are available or VBLENDV if AVX is available.
14626   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14627   if (Cond.getOpcode() == ISD::SETCC &&
14628       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14629        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14630       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14631     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14632     int SSECC = translateX86FSETCC(
14633         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14634
14635     if (SSECC != 8) {
14636       if (Subtarget->hasAVX512()) {
14637         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14638                                   DAG.getConstant(SSECC, DL, MVT::i8));
14639         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14640       }
14641
14642       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14643                                 DAG.getConstant(SSECC, DL, MVT::i8));
14644
14645       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14646       // of 3 logic instructions for size savings and potentially speed.
14647       // Unfortunately, there is no scalar form of VBLENDV.
14648
14649       // If either operand is a constant, don't try this. We can expect to
14650       // optimize away at least one of the logic instructions later in that
14651       // case, so that sequence would be faster than a variable blend.
14652
14653       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14654       // uses XMM0 as the selection register. That may need just as many
14655       // instructions as the AND/ANDN/OR sequence due to register moves, so
14656       // don't bother.
14657
14658       if (Subtarget->hasAVX() &&
14659           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14660
14661         // Convert to vectors, do a VSELECT, and convert back to scalar.
14662         // All of the conversions should be optimized away.
14663
14664         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14665         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14666         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14667         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14668
14669         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14670         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14671
14672         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14673
14674         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14675                            VSel, DAG.getIntPtrConstant(0, DL));
14676       }
14677       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14678       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14679       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14680     }
14681   }
14682
14683   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14684     SDValue Op1Scalar;
14685     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14686       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14687     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14688       Op1Scalar = Op1.getOperand(0);
14689     SDValue Op2Scalar;
14690     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14691       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14692     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14693       Op2Scalar = Op2.getOperand(0);
14694     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14695       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14696                                       Op1Scalar.getValueType(),
14697                                       Cond, Op1Scalar, Op2Scalar);
14698       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14699         return DAG.getBitcast(VT, newSelect);
14700       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14701       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14702                          DAG.getIntPtrConstant(0, DL));
14703     }
14704   }
14705
14706   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14707     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14708     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14709                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14710     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14711                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14712     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14713                                     Cond, Op1, Op2);
14714     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14715   }
14716
14717   if (Cond.getOpcode() == ISD::SETCC) {
14718     SDValue NewCond = LowerSETCC(Cond, DAG);
14719     if (NewCond.getNode())
14720       Cond = NewCond;
14721   }
14722
14723   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14724   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14725   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14726   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14727   if (Cond.getOpcode() == X86ISD::SETCC &&
14728       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14729       isZero(Cond.getOperand(1).getOperand(1))) {
14730     SDValue Cmp = Cond.getOperand(1);
14731
14732     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14733
14734     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14735         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14736       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14737
14738       SDValue CmpOp0 = Cmp.getOperand(0);
14739       // Apply further optimizations for special cases
14740       // (select (x != 0), -1, 0) -> neg & sbb
14741       // (select (x == 0), 0, -1) -> neg & sbb
14742       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14743         if (YC->isNullValue() &&
14744             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14745           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14746           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14747                                     DAG.getConstant(0, DL,
14748                                                     CmpOp0.getValueType()),
14749                                     CmpOp0);
14750           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14751                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14752                                     SDValue(Neg.getNode(), 1));
14753           return Res;
14754         }
14755
14756       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14757                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14758       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14759
14760       SDValue Res =   // Res = 0 or -1.
14761         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14762                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14763
14764       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14765         Res = DAG.getNOT(DL, Res, Res.getValueType());
14766
14767       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14768       if (!N2C || !N2C->isNullValue())
14769         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14770       return Res;
14771     }
14772   }
14773
14774   // Look past (and (setcc_carry (cmp ...)), 1).
14775   if (Cond.getOpcode() == ISD::AND &&
14776       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14777     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14778     if (C && C->getAPIntValue() == 1)
14779       Cond = Cond.getOperand(0);
14780   }
14781
14782   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14783   // setting operand in place of the X86ISD::SETCC.
14784   unsigned CondOpcode = Cond.getOpcode();
14785   if (CondOpcode == X86ISD::SETCC ||
14786       CondOpcode == X86ISD::SETCC_CARRY) {
14787     CC = Cond.getOperand(0);
14788
14789     SDValue Cmp = Cond.getOperand(1);
14790     unsigned Opc = Cmp.getOpcode();
14791     MVT VT = Op.getSimpleValueType();
14792
14793     bool IllegalFPCMov = false;
14794     if (VT.isFloatingPoint() && !VT.isVector() &&
14795         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14796       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14797
14798     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14799         Opc == X86ISD::BT) { // FIXME
14800       Cond = Cmp;
14801       addTest = false;
14802     }
14803   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14804              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14805              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14806               Cond.getOperand(0).getValueType() != MVT::i8)) {
14807     SDValue LHS = Cond.getOperand(0);
14808     SDValue RHS = Cond.getOperand(1);
14809     unsigned X86Opcode;
14810     unsigned X86Cond;
14811     SDVTList VTs;
14812     switch (CondOpcode) {
14813     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14814     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14815     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14816     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14817     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14818     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14819     default: llvm_unreachable("unexpected overflowing operator");
14820     }
14821     if (CondOpcode == ISD::UMULO)
14822       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14823                           MVT::i32);
14824     else
14825       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14826
14827     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14828
14829     if (CondOpcode == ISD::UMULO)
14830       Cond = X86Op.getValue(2);
14831     else
14832       Cond = X86Op.getValue(1);
14833
14834     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14835     addTest = false;
14836   }
14837
14838   if (addTest) {
14839     // Look past the truncate if the high bits are known zero.
14840     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14841       Cond = Cond.getOperand(0);
14842
14843     // We know the result of AND is compared against zero. Try to match
14844     // it to BT.
14845     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14846       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
14847         CC = NewSetCC.getOperand(0);
14848         Cond = NewSetCC.getOperand(1);
14849         addTest = false;
14850       }
14851     }
14852   }
14853
14854   if (addTest) {
14855     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14856     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14857   }
14858
14859   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14860   // a <  b ?  0 : -1 -> RES = setcc_carry
14861   // a >= b ? -1 :  0 -> RES = setcc_carry
14862   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14863   if (Cond.getOpcode() == X86ISD::SUB) {
14864     Cond = ConvertCmpIfNecessary(Cond, DAG);
14865     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14866
14867     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14868         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14869       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14870                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14871                                 Cond);
14872       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14873         return DAG.getNOT(DL, Res, Res.getValueType());
14874       return Res;
14875     }
14876   }
14877
14878   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14879   // widen the cmov and push the truncate through. This avoids introducing a new
14880   // branch during isel and doesn't add any extensions.
14881   if (Op.getValueType() == MVT::i8 &&
14882       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14883     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14884     if (T1.getValueType() == T2.getValueType() &&
14885         // Blacklist CopyFromReg to avoid partial register stalls.
14886         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14887       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14888       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14889       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14890     }
14891   }
14892
14893   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14894   // condition is true.
14895   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14896   SDValue Ops[] = { Op2, Op1, CC, Cond };
14897   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14898 }
14899
14900 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14901                                        const X86Subtarget *Subtarget,
14902                                        SelectionDAG &DAG) {
14903   MVT VT = Op->getSimpleValueType(0);
14904   SDValue In = Op->getOperand(0);
14905   MVT InVT = In.getSimpleValueType();
14906   MVT VTElt = VT.getVectorElementType();
14907   MVT InVTElt = InVT.getVectorElementType();
14908   SDLoc dl(Op);
14909
14910   // SKX processor
14911   if ((InVTElt == MVT::i1) &&
14912       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14913         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14914
14915        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14916         VTElt.getSizeInBits() <= 16)) ||
14917
14918        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14919         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14920
14921        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14922         VTElt.getSizeInBits() >= 32))))
14923     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14924
14925   unsigned int NumElts = VT.getVectorNumElements();
14926
14927   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14928     return SDValue();
14929
14930   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14931     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14932       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14933     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14934   }
14935
14936   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14937   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14938   SDValue NegOne =
14939    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14940                    ExtVT);
14941   SDValue Zero =
14942    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14943
14944   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14945   if (VT.is512BitVector())
14946     return V;
14947   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14948 }
14949
14950 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14951                                              const X86Subtarget *Subtarget,
14952                                              SelectionDAG &DAG) {
14953   SDValue In = Op->getOperand(0);
14954   MVT VT = Op->getSimpleValueType(0);
14955   MVT InVT = In.getSimpleValueType();
14956   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14957
14958   MVT InSVT = InVT.getVectorElementType();
14959   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
14960
14961   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14962     return SDValue();
14963   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14964     return SDValue();
14965
14966   SDLoc dl(Op);
14967
14968   // SSE41 targets can use the pmovsx* instructions directly.
14969   if (Subtarget->hasSSE41())
14970     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14971
14972   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14973   SDValue Curr = In;
14974   MVT CurrVT = InVT;
14975
14976   // As SRAI is only available on i16/i32 types, we expand only up to i32
14977   // and handle i64 separately.
14978   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
14979     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14980     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14981     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14982     Curr = DAG.getBitcast(CurrVT, Curr);
14983   }
14984
14985   SDValue SignExt = Curr;
14986   if (CurrVT != InVT) {
14987     unsigned SignExtShift =
14988         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
14989     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14990                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14991   }
14992
14993   if (CurrVT == VT)
14994     return SignExt;
14995
14996   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14997     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14998                                DAG.getConstant(31, dl, MVT::i8));
14999     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15000     return DAG.getBitcast(VT, Ext);
15001   }
15002
15003   return SDValue();
15004 }
15005
15006 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15007                                 SelectionDAG &DAG) {
15008   MVT VT = Op->getSimpleValueType(0);
15009   SDValue In = Op->getOperand(0);
15010   MVT InVT = In.getSimpleValueType();
15011   SDLoc dl(Op);
15012
15013   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15014     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15015
15016   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15017       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15018       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15019     return SDValue();
15020
15021   if (Subtarget->hasInt256())
15022     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15023
15024   // Optimize vectors in AVX mode
15025   // Sign extend  v8i16 to v8i32 and
15026   //              v4i32 to v4i64
15027   //
15028   // Divide input vector into two parts
15029   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15030   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15031   // concat the vectors to original VT
15032
15033   unsigned NumElems = InVT.getVectorNumElements();
15034   SDValue Undef = DAG.getUNDEF(InVT);
15035
15036   SmallVector<int,8> ShufMask1(NumElems, -1);
15037   for (unsigned i = 0; i != NumElems/2; ++i)
15038     ShufMask1[i] = i;
15039
15040   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15041
15042   SmallVector<int,8> ShufMask2(NumElems, -1);
15043   for (unsigned i = 0; i != NumElems/2; ++i)
15044     ShufMask2[i] = i + NumElems/2;
15045
15046   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15047
15048   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15049                                 VT.getVectorNumElements()/2);
15050
15051   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15052   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15053
15054   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15055 }
15056
15057 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15058 // may emit an illegal shuffle but the expansion is still better than scalar
15059 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15060 // we'll emit a shuffle and a arithmetic shift.
15061 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15062 // TODO: It is possible to support ZExt by zeroing the undef values during
15063 // the shuffle phase or after the shuffle.
15064 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15065                                  SelectionDAG &DAG) {
15066   MVT RegVT = Op.getSimpleValueType();
15067   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15068   assert(RegVT.isInteger() &&
15069          "We only custom lower integer vector sext loads.");
15070
15071   // Nothing useful we can do without SSE2 shuffles.
15072   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15073
15074   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15075   SDLoc dl(Ld);
15076   EVT MemVT = Ld->getMemoryVT();
15077   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15078   unsigned RegSz = RegVT.getSizeInBits();
15079
15080   ISD::LoadExtType Ext = Ld->getExtensionType();
15081
15082   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15083          && "Only anyext and sext are currently implemented.");
15084   assert(MemVT != RegVT && "Cannot extend to the same type");
15085   assert(MemVT.isVector() && "Must load a vector from memory");
15086
15087   unsigned NumElems = RegVT.getVectorNumElements();
15088   unsigned MemSz = MemVT.getSizeInBits();
15089   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15090
15091   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15092     // The only way in which we have a legal 256-bit vector result but not the
15093     // integer 256-bit operations needed to directly lower a sextload is if we
15094     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15095     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15096     // correctly legalized. We do this late to allow the canonical form of
15097     // sextload to persist throughout the rest of the DAG combiner -- it wants
15098     // to fold together any extensions it can, and so will fuse a sign_extend
15099     // of an sextload into a sextload targeting a wider value.
15100     SDValue Load;
15101     if (MemSz == 128) {
15102       // Just switch this to a normal load.
15103       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15104                                        "it must be a legal 128-bit vector "
15105                                        "type!");
15106       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15107                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15108                   Ld->isInvariant(), Ld->getAlignment());
15109     } else {
15110       assert(MemSz < 128 &&
15111              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15112       // Do an sext load to a 128-bit vector type. We want to use the same
15113       // number of elements, but elements half as wide. This will end up being
15114       // recursively lowered by this routine, but will succeed as we definitely
15115       // have all the necessary features if we're using AVX1.
15116       EVT HalfEltVT =
15117           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15118       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15119       Load =
15120           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15121                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15122                          Ld->isNonTemporal(), Ld->isInvariant(),
15123                          Ld->getAlignment());
15124     }
15125
15126     // Replace chain users with the new chain.
15127     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15128     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15129
15130     // Finally, do a normal sign-extend to the desired register.
15131     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15132   }
15133
15134   // All sizes must be a power of two.
15135   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15136          "Non-power-of-two elements are not custom lowered!");
15137
15138   // Attempt to load the original value using scalar loads.
15139   // Find the largest scalar type that divides the total loaded size.
15140   MVT SclrLoadTy = MVT::i8;
15141   for (MVT Tp : MVT::integer_valuetypes()) {
15142     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15143       SclrLoadTy = Tp;
15144     }
15145   }
15146
15147   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15148   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15149       (64 <= MemSz))
15150     SclrLoadTy = MVT::f64;
15151
15152   // Calculate the number of scalar loads that we need to perform
15153   // in order to load our vector from memory.
15154   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15155
15156   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15157          "Can only lower sext loads with a single scalar load!");
15158
15159   unsigned loadRegZize = RegSz;
15160   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15161     loadRegZize = 128;
15162
15163   // Represent our vector as a sequence of elements which are the
15164   // largest scalar that we can load.
15165   EVT LoadUnitVecVT = EVT::getVectorVT(
15166       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15167
15168   // Represent the data using the same element type that is stored in
15169   // memory. In practice, we ''widen'' MemVT.
15170   EVT WideVecVT =
15171       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15172                        loadRegZize / MemVT.getScalarSizeInBits());
15173
15174   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15175          "Invalid vector type");
15176
15177   // We can't shuffle using an illegal type.
15178   assert(TLI.isTypeLegal(WideVecVT) &&
15179          "We only lower types that form legal widened vector types");
15180
15181   SmallVector<SDValue, 8> Chains;
15182   SDValue Ptr = Ld->getBasePtr();
15183   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15184                                       TLI.getPointerTy(DAG.getDataLayout()));
15185   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15186
15187   for (unsigned i = 0; i < NumLoads; ++i) {
15188     // Perform a single load.
15189     SDValue ScalarLoad =
15190         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15191                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15192                     Ld->getAlignment());
15193     Chains.push_back(ScalarLoad.getValue(1));
15194     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15195     // another round of DAGCombining.
15196     if (i == 0)
15197       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15198     else
15199       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15200                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15201
15202     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15203   }
15204
15205   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15206
15207   // Bitcast the loaded value to a vector of the original element type, in
15208   // the size of the target vector type.
15209   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15210   unsigned SizeRatio = RegSz / MemSz;
15211
15212   if (Ext == ISD::SEXTLOAD) {
15213     // If we have SSE4.1, we can directly emit a VSEXT node.
15214     if (Subtarget->hasSSE41()) {
15215       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15216       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15217       return Sext;
15218     }
15219
15220     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15221     // lanes.
15222     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15223            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15224
15225     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15226     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15227     return Shuff;
15228   }
15229
15230   // Redistribute the loaded elements into the different locations.
15231   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15232   for (unsigned i = 0; i != NumElems; ++i)
15233     ShuffleVec[i * SizeRatio] = i;
15234
15235   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15236                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15237
15238   // Bitcast to the requested type.
15239   Shuff = DAG.getBitcast(RegVT, Shuff);
15240   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15241   return Shuff;
15242 }
15243
15244 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15245 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15246 // from the AND / OR.
15247 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15248   Opc = Op.getOpcode();
15249   if (Opc != ISD::OR && Opc != ISD::AND)
15250     return false;
15251   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15252           Op.getOperand(0).hasOneUse() &&
15253           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15254           Op.getOperand(1).hasOneUse());
15255 }
15256
15257 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15258 // 1 and that the SETCC node has a single use.
15259 static bool isXor1OfSetCC(SDValue Op) {
15260   if (Op.getOpcode() != ISD::XOR)
15261     return false;
15262   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15263   if (N1C && N1C->getAPIntValue() == 1) {
15264     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15265       Op.getOperand(0).hasOneUse();
15266   }
15267   return false;
15268 }
15269
15270 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15271   bool addTest = true;
15272   SDValue Chain = Op.getOperand(0);
15273   SDValue Cond  = Op.getOperand(1);
15274   SDValue Dest  = Op.getOperand(2);
15275   SDLoc dl(Op);
15276   SDValue CC;
15277   bool Inverted = false;
15278
15279   if (Cond.getOpcode() == ISD::SETCC) {
15280     // Check for setcc([su]{add,sub,mul}o == 0).
15281     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15282         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15283         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15284         Cond.getOperand(0).getResNo() == 1 &&
15285         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15286          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15287          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15288          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15289          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15290          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15291       Inverted = true;
15292       Cond = Cond.getOperand(0);
15293     } else {
15294       SDValue NewCond = LowerSETCC(Cond, DAG);
15295       if (NewCond.getNode())
15296         Cond = NewCond;
15297     }
15298   }
15299 #if 0
15300   // FIXME: LowerXALUO doesn't handle these!!
15301   else if (Cond.getOpcode() == X86ISD::ADD  ||
15302            Cond.getOpcode() == X86ISD::SUB  ||
15303            Cond.getOpcode() == X86ISD::SMUL ||
15304            Cond.getOpcode() == X86ISD::UMUL)
15305     Cond = LowerXALUO(Cond, DAG);
15306 #endif
15307
15308   // Look pass (and (setcc_carry (cmp ...)), 1).
15309   if (Cond.getOpcode() == ISD::AND &&
15310       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15311     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15312     if (C && C->getAPIntValue() == 1)
15313       Cond = Cond.getOperand(0);
15314   }
15315
15316   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15317   // setting operand in place of the X86ISD::SETCC.
15318   unsigned CondOpcode = Cond.getOpcode();
15319   if (CondOpcode == X86ISD::SETCC ||
15320       CondOpcode == X86ISD::SETCC_CARRY) {
15321     CC = Cond.getOperand(0);
15322
15323     SDValue Cmp = Cond.getOperand(1);
15324     unsigned Opc = Cmp.getOpcode();
15325     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15326     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15327       Cond = Cmp;
15328       addTest = false;
15329     } else {
15330       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15331       default: break;
15332       case X86::COND_O:
15333       case X86::COND_B:
15334         // These can only come from an arithmetic instruction with overflow,
15335         // e.g. SADDO, UADDO.
15336         Cond = Cond.getNode()->getOperand(1);
15337         addTest = false;
15338         break;
15339       }
15340     }
15341   }
15342   CondOpcode = Cond.getOpcode();
15343   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15344       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15345       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15346        Cond.getOperand(0).getValueType() != MVT::i8)) {
15347     SDValue LHS = Cond.getOperand(0);
15348     SDValue RHS = Cond.getOperand(1);
15349     unsigned X86Opcode;
15350     unsigned X86Cond;
15351     SDVTList VTs;
15352     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15353     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15354     // X86ISD::INC).
15355     switch (CondOpcode) {
15356     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15357     case ISD::SADDO:
15358       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15359         if (C->isOne()) {
15360           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15361           break;
15362         }
15363       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15364     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15365     case ISD::SSUBO:
15366       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15367         if (C->isOne()) {
15368           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15369           break;
15370         }
15371       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15372     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15373     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15374     default: llvm_unreachable("unexpected overflowing operator");
15375     }
15376     if (Inverted)
15377       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15378     if (CondOpcode == ISD::UMULO)
15379       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15380                           MVT::i32);
15381     else
15382       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15383
15384     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15385
15386     if (CondOpcode == ISD::UMULO)
15387       Cond = X86Op.getValue(2);
15388     else
15389       Cond = X86Op.getValue(1);
15390
15391     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15392     addTest = false;
15393   } else {
15394     unsigned CondOpc;
15395     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15396       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15397       if (CondOpc == ISD::OR) {
15398         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15399         // two branches instead of an explicit OR instruction with a
15400         // separate test.
15401         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15402             isX86LogicalCmp(Cmp)) {
15403           CC = Cond.getOperand(0).getOperand(0);
15404           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15405                               Chain, Dest, CC, Cmp);
15406           CC = Cond.getOperand(1).getOperand(0);
15407           Cond = Cmp;
15408           addTest = false;
15409         }
15410       } else { // ISD::AND
15411         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15412         // two branches instead of an explicit AND instruction with a
15413         // separate test. However, we only do this if this block doesn't
15414         // have a fall-through edge, because this requires an explicit
15415         // jmp when the condition is false.
15416         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15417             isX86LogicalCmp(Cmp) &&
15418             Op.getNode()->hasOneUse()) {
15419           X86::CondCode CCode =
15420             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15421           CCode = X86::GetOppositeBranchCondition(CCode);
15422           CC = DAG.getConstant(CCode, dl, MVT::i8);
15423           SDNode *User = *Op.getNode()->use_begin();
15424           // Look for an unconditional branch following this conditional branch.
15425           // We need this because we need to reverse the successors in order
15426           // to implement FCMP_OEQ.
15427           if (User->getOpcode() == ISD::BR) {
15428             SDValue FalseBB = User->getOperand(1);
15429             SDNode *NewBR =
15430               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15431             assert(NewBR == User);
15432             (void)NewBR;
15433             Dest = FalseBB;
15434
15435             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15436                                 Chain, Dest, CC, Cmp);
15437             X86::CondCode CCode =
15438               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15439             CCode = X86::GetOppositeBranchCondition(CCode);
15440             CC = DAG.getConstant(CCode, dl, MVT::i8);
15441             Cond = Cmp;
15442             addTest = false;
15443           }
15444         }
15445       }
15446     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15447       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15448       // It should be transformed during dag combiner except when the condition
15449       // is set by a arithmetics with overflow node.
15450       X86::CondCode CCode =
15451         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15452       CCode = X86::GetOppositeBranchCondition(CCode);
15453       CC = DAG.getConstant(CCode, dl, MVT::i8);
15454       Cond = Cond.getOperand(0).getOperand(1);
15455       addTest = false;
15456     } else if (Cond.getOpcode() == ISD::SETCC &&
15457                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15458       // For FCMP_OEQ, we can emit
15459       // two branches instead of an explicit AND instruction with a
15460       // separate test. However, we only do this if this block doesn't
15461       // have a fall-through edge, because this requires an explicit
15462       // jmp when the condition is false.
15463       if (Op.getNode()->hasOneUse()) {
15464         SDNode *User = *Op.getNode()->use_begin();
15465         // Look for an unconditional branch following this conditional branch.
15466         // We need this because we need to reverse the successors in order
15467         // to implement FCMP_OEQ.
15468         if (User->getOpcode() == ISD::BR) {
15469           SDValue FalseBB = User->getOperand(1);
15470           SDNode *NewBR =
15471             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15472           assert(NewBR == User);
15473           (void)NewBR;
15474           Dest = FalseBB;
15475
15476           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15477                                     Cond.getOperand(0), Cond.getOperand(1));
15478           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15479           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15480           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15481                               Chain, Dest, CC, Cmp);
15482           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15483           Cond = Cmp;
15484           addTest = false;
15485         }
15486       }
15487     } else if (Cond.getOpcode() == ISD::SETCC &&
15488                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15489       // For FCMP_UNE, we can emit
15490       // two branches instead of an explicit AND instruction with a
15491       // separate test. However, we only do this if this block doesn't
15492       // have a fall-through edge, because this requires an explicit
15493       // jmp when the condition is false.
15494       if (Op.getNode()->hasOneUse()) {
15495         SDNode *User = *Op.getNode()->use_begin();
15496         // Look for an unconditional branch following this conditional branch.
15497         // We need this because we need to reverse the successors in order
15498         // to implement FCMP_UNE.
15499         if (User->getOpcode() == ISD::BR) {
15500           SDValue FalseBB = User->getOperand(1);
15501           SDNode *NewBR =
15502             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15503           assert(NewBR == User);
15504           (void)NewBR;
15505
15506           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15507                                     Cond.getOperand(0), Cond.getOperand(1));
15508           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15509           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15510           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15511                               Chain, Dest, CC, Cmp);
15512           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15513           Cond = Cmp;
15514           addTest = false;
15515           Dest = FalseBB;
15516         }
15517       }
15518     }
15519   }
15520
15521   if (addTest) {
15522     // Look pass the truncate if the high bits are known zero.
15523     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15524         Cond = Cond.getOperand(0);
15525
15526     // We know the result of AND is compared against zero. Try to match
15527     // it to BT.
15528     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15529       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15530         CC = NewSetCC.getOperand(0);
15531         Cond = NewSetCC.getOperand(1);
15532         addTest = false;
15533       }
15534     }
15535   }
15536
15537   if (addTest) {
15538     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15539     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15540     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15541   }
15542   Cond = ConvertCmpIfNecessary(Cond, DAG);
15543   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15544                      Chain, Dest, CC, Cond);
15545 }
15546
15547 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15548 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15549 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15550 // that the guard pages used by the OS virtual memory manager are allocated in
15551 // correct sequence.
15552 SDValue
15553 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15554                                            SelectionDAG &DAG) const {
15555   MachineFunction &MF = DAG.getMachineFunction();
15556   bool SplitStack = MF.shouldSplitStack();
15557   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15558                SplitStack;
15559   SDLoc dl(Op);
15560
15561   if (!Lower) {
15562     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15563     SDNode* Node = Op.getNode();
15564
15565     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15566     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15567         " not tell us which reg is the stack pointer!");
15568     EVT VT = Node->getValueType(0);
15569     SDValue Tmp1 = SDValue(Node, 0);
15570     SDValue Tmp2 = SDValue(Node, 1);
15571     SDValue Tmp3 = Node->getOperand(2);
15572     SDValue Chain = Tmp1.getOperand(0);
15573
15574     // Chain the dynamic stack allocation so that it doesn't modify the stack
15575     // pointer when other instructions are using the stack.
15576     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15577         SDLoc(Node));
15578
15579     SDValue Size = Tmp2.getOperand(1);
15580     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15581     Chain = SP.getValue(1);
15582     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15583     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15584     unsigned StackAlign = TFI.getStackAlignment();
15585     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15586     if (Align > StackAlign)
15587       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15588           DAG.getConstant(-(uint64_t)Align, dl, VT));
15589     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15590
15591     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15592         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15593         SDLoc(Node));
15594
15595     SDValue Ops[2] = { Tmp1, Tmp2 };
15596     return DAG.getMergeValues(Ops, dl);
15597   }
15598
15599   // Get the inputs.
15600   SDValue Chain = Op.getOperand(0);
15601   SDValue Size  = Op.getOperand(1);
15602   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15603   EVT VT = Op.getNode()->getValueType(0);
15604
15605   bool Is64Bit = Subtarget->is64Bit();
15606   MVT SPTy = getPointerTy(DAG.getDataLayout());
15607
15608   if (SplitStack) {
15609     MachineRegisterInfo &MRI = MF.getRegInfo();
15610
15611     if (Is64Bit) {
15612       // The 64 bit implementation of segmented stacks needs to clobber both r10
15613       // r11. This makes it impossible to use it along with nested parameters.
15614       const Function *F = MF.getFunction();
15615
15616       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15617            I != E; ++I)
15618         if (I->hasNestAttr())
15619           report_fatal_error("Cannot use segmented stacks with functions that "
15620                              "have nested arguments.");
15621     }
15622
15623     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15624     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15625     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15626     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15627                                 DAG.getRegister(Vreg, SPTy));
15628     SDValue Ops1[2] = { Value, Chain };
15629     return DAG.getMergeValues(Ops1, dl);
15630   } else {
15631     SDValue Flag;
15632     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15633
15634     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15635     Flag = Chain.getValue(1);
15636     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15637
15638     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15639
15640     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15641     unsigned SPReg = RegInfo->getStackRegister();
15642     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15643     Chain = SP.getValue(1);
15644
15645     if (Align) {
15646       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15647                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15648       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15649     }
15650
15651     SDValue Ops1[2] = { SP, Chain };
15652     return DAG.getMergeValues(Ops1, dl);
15653   }
15654 }
15655
15656 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15657   MachineFunction &MF = DAG.getMachineFunction();
15658   auto PtrVT = getPointerTy(MF.getDataLayout());
15659   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15660
15661   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15662   SDLoc DL(Op);
15663
15664   if (!Subtarget->is64Bit() ||
15665       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15666     // vastart just stores the address of the VarArgsFrameIndex slot into the
15667     // memory location argument.
15668     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15669     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15670                         MachinePointerInfo(SV), false, false, 0);
15671   }
15672
15673   // __va_list_tag:
15674   //   gp_offset         (0 - 6 * 8)
15675   //   fp_offset         (48 - 48 + 8 * 16)
15676   //   overflow_arg_area (point to parameters coming in memory).
15677   //   reg_save_area
15678   SmallVector<SDValue, 8> MemOps;
15679   SDValue FIN = Op.getOperand(1);
15680   // Store gp_offset
15681   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15682                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15683                                                DL, MVT::i32),
15684                                FIN, MachinePointerInfo(SV), false, false, 0);
15685   MemOps.push_back(Store);
15686
15687   // Store fp_offset
15688   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15689   Store = DAG.getStore(Op.getOperand(0), DL,
15690                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15691                                        MVT::i32),
15692                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15693   MemOps.push_back(Store);
15694
15695   // Store ptr to overflow_arg_area
15696   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15697   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15698   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15699                        MachinePointerInfo(SV, 8),
15700                        false, false, 0);
15701   MemOps.push_back(Store);
15702
15703   // Store ptr to reg_save_area.
15704   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15705       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15706   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15707   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15708       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15709   MemOps.push_back(Store);
15710   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15711 }
15712
15713 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15714   assert(Subtarget->is64Bit() &&
15715          "LowerVAARG only handles 64-bit va_arg!");
15716   assert(Op.getNode()->getNumOperands() == 4);
15717
15718   MachineFunction &MF = DAG.getMachineFunction();
15719   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15720     // The Win64 ABI uses char* instead of a structure.
15721     return DAG.expandVAArg(Op.getNode());
15722
15723   SDValue Chain = Op.getOperand(0);
15724   SDValue SrcPtr = Op.getOperand(1);
15725   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15726   unsigned Align = Op.getConstantOperandVal(3);
15727   SDLoc dl(Op);
15728
15729   EVT ArgVT = Op.getNode()->getValueType(0);
15730   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15731   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15732   uint8_t ArgMode;
15733
15734   // Decide which area this value should be read from.
15735   // TODO: Implement the AMD64 ABI in its entirety. This simple
15736   // selection mechanism works only for the basic types.
15737   if (ArgVT == MVT::f80) {
15738     llvm_unreachable("va_arg for f80 not yet implemented");
15739   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15740     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15741   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15742     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15743   } else {
15744     llvm_unreachable("Unhandled argument type in LowerVAARG");
15745   }
15746
15747   if (ArgMode == 2) {
15748     // Sanity Check: Make sure using fp_offset makes sense.
15749     assert(!Subtarget->useSoftFloat() &&
15750            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15751            Subtarget->hasSSE1());
15752   }
15753
15754   // Insert VAARG_64 node into the DAG
15755   // VAARG_64 returns two values: Variable Argument Address, Chain
15756   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15757                        DAG.getConstant(ArgMode, dl, MVT::i8),
15758                        DAG.getConstant(Align, dl, MVT::i32)};
15759   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15760   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15761                                           VTs, InstOps, MVT::i64,
15762                                           MachinePointerInfo(SV),
15763                                           /*Align=*/0,
15764                                           /*Volatile=*/false,
15765                                           /*ReadMem=*/true,
15766                                           /*WriteMem=*/true);
15767   Chain = VAARG.getValue(1);
15768
15769   // Load the next argument and return it
15770   return DAG.getLoad(ArgVT, dl,
15771                      Chain,
15772                      VAARG,
15773                      MachinePointerInfo(),
15774                      false, false, false, 0);
15775 }
15776
15777 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15778                            SelectionDAG &DAG) {
15779   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15780   // where a va_list is still an i8*.
15781   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15782   if (Subtarget->isCallingConvWin64(
15783         DAG.getMachineFunction().getFunction()->getCallingConv()))
15784     // Probably a Win64 va_copy.
15785     return DAG.expandVACopy(Op.getNode());
15786
15787   SDValue Chain = Op.getOperand(0);
15788   SDValue DstPtr = Op.getOperand(1);
15789   SDValue SrcPtr = Op.getOperand(2);
15790   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15791   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15792   SDLoc DL(Op);
15793
15794   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15795                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15796                        false, false,
15797                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15798 }
15799
15800 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15801 // amount is a constant. Takes immediate version of shift as input.
15802 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15803                                           SDValue SrcOp, uint64_t ShiftAmt,
15804                                           SelectionDAG &DAG) {
15805   MVT ElementType = VT.getVectorElementType();
15806
15807   // Fold this packed shift into its first operand if ShiftAmt is 0.
15808   if (ShiftAmt == 0)
15809     return SrcOp;
15810
15811   // Check for ShiftAmt >= element width
15812   if (ShiftAmt >= ElementType.getSizeInBits()) {
15813     if (Opc == X86ISD::VSRAI)
15814       ShiftAmt = ElementType.getSizeInBits() - 1;
15815     else
15816       return DAG.getConstant(0, dl, VT);
15817   }
15818
15819   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15820          && "Unknown target vector shift-by-constant node");
15821
15822   // Fold this packed vector shift into a build vector if SrcOp is a
15823   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15824   if (VT == SrcOp.getSimpleValueType() &&
15825       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15826     SmallVector<SDValue, 8> Elts;
15827     unsigned NumElts = SrcOp->getNumOperands();
15828     ConstantSDNode *ND;
15829
15830     switch(Opc) {
15831     default: llvm_unreachable(nullptr);
15832     case X86ISD::VSHLI:
15833       for (unsigned i=0; i!=NumElts; ++i) {
15834         SDValue CurrentOp = SrcOp->getOperand(i);
15835         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15836           Elts.push_back(CurrentOp);
15837           continue;
15838         }
15839         ND = cast<ConstantSDNode>(CurrentOp);
15840         const APInt &C = ND->getAPIntValue();
15841         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15842       }
15843       break;
15844     case X86ISD::VSRLI:
15845       for (unsigned i=0; i!=NumElts; ++i) {
15846         SDValue CurrentOp = SrcOp->getOperand(i);
15847         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15848           Elts.push_back(CurrentOp);
15849           continue;
15850         }
15851         ND = cast<ConstantSDNode>(CurrentOp);
15852         const APInt &C = ND->getAPIntValue();
15853         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15854       }
15855       break;
15856     case X86ISD::VSRAI:
15857       for (unsigned i=0; i!=NumElts; ++i) {
15858         SDValue CurrentOp = SrcOp->getOperand(i);
15859         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15860           Elts.push_back(CurrentOp);
15861           continue;
15862         }
15863         ND = cast<ConstantSDNode>(CurrentOp);
15864         const APInt &C = ND->getAPIntValue();
15865         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15866       }
15867       break;
15868     }
15869
15870     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15871   }
15872
15873   return DAG.getNode(Opc, dl, VT, SrcOp,
15874                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15875 }
15876
15877 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15878 // may or may not be a constant. Takes immediate version of shift as input.
15879 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15880                                    SDValue SrcOp, SDValue ShAmt,
15881                                    SelectionDAG &DAG) {
15882   MVT SVT = ShAmt.getSimpleValueType();
15883   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15884
15885   // Catch shift-by-constant.
15886   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15887     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15888                                       CShAmt->getZExtValue(), DAG);
15889
15890   // Change opcode to non-immediate version
15891   switch (Opc) {
15892     default: llvm_unreachable("Unknown target vector shift node");
15893     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15894     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15895     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15896   }
15897
15898   const X86Subtarget &Subtarget =
15899       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15900   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15901       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15902     // Let the shuffle legalizer expand this shift amount node.
15903     SDValue Op0 = ShAmt.getOperand(0);
15904     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15905     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15906   } else {
15907     // Need to build a vector containing shift amount.
15908     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15909     SmallVector<SDValue, 4> ShOps;
15910     ShOps.push_back(ShAmt);
15911     if (SVT == MVT::i32) {
15912       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15913       ShOps.push_back(DAG.getUNDEF(SVT));
15914     }
15915     ShOps.push_back(DAG.getUNDEF(SVT));
15916
15917     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15918     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15919   }
15920
15921   // The return type has to be a 128-bit type with the same element
15922   // type as the input type.
15923   MVT EltVT = VT.getVectorElementType();
15924   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15925
15926   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15927   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15928 }
15929
15930 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15931 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15932 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15933 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15934                                     SDValue PreservedSrc,
15935                                     const X86Subtarget *Subtarget,
15936                                     SelectionDAG &DAG) {
15937     MVT VT = Op.getSimpleValueType();
15938     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
15939     SDValue VMask;
15940     unsigned OpcodeSelect = ISD::VSELECT;
15941     SDLoc dl(Op);
15942
15943     if (isAllOnes(Mask))
15944       return Op;
15945
15946     if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
15947       MVT newMaskVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
15948       VMask = DAG.getBitcast(MaskVT,
15949                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15950     } else {
15951       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
15952                                        Mask.getSimpleValueType().getSizeInBits());
15953       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15954       // are extracted by EXTRACT_SUBVECTOR.
15955       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15956                           DAG.getBitcast(BitcastVT, Mask),
15957                           DAG.getIntPtrConstant(0, dl));
15958     }
15959
15960     switch (Op.getOpcode()) {
15961     default: break;
15962     case X86ISD::PCMPEQM:
15963     case X86ISD::PCMPGTM:
15964     case X86ISD::CMPM:
15965     case X86ISD::CMPMU:
15966       return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15967     case X86ISD::VFPCLASS:
15968       return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15969     case X86ISD::VTRUNC:
15970     case X86ISD::VTRUNCS:
15971     case X86ISD::VTRUNCUS:
15972       // We can't use ISD::VSELECT here because it is not always "Legal"
15973       // for the destination type. For example vpmovqb require only AVX512
15974       // and vselect that can operate on byte element type require BWI
15975       OpcodeSelect = X86ISD::SELECT;
15976       break;
15977     }
15978     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15979       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15980     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15981 }
15982
15983 /// \brief Creates an SDNode for a predicated scalar operation.
15984 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15985 /// The mask is coming as MVT::i8 and it should be truncated
15986 /// to MVT::i1 while lowering masking intrinsics.
15987 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15988 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15989 /// for a scalar instruction.
15990 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15991                                     SDValue PreservedSrc,
15992                                     const X86Subtarget *Subtarget,
15993                                     SelectionDAG &DAG) {
15994   if (isAllOnes(Mask))
15995     return Op;
15996
15997   MVT VT = Op.getSimpleValueType();
15998   SDLoc dl(Op);
15999   // The mask should be of type MVT::i1
16000   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16001
16002   if (Op.getOpcode() == X86ISD::FSETCC)
16003     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16004   if (Op.getOpcode() == X86ISD::VFPCLASS)
16005     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16006
16007   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16008     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16009   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16010 }
16011
16012 static int getSEHRegistrationNodeSize(const Function *Fn) {
16013   if (!Fn->hasPersonalityFn())
16014     report_fatal_error(
16015         "querying registration node size for function without personality");
16016   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16017   // WinEHStatePass for the full struct definition.
16018   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16019   case EHPersonality::MSVC_X86SEH: return 24;
16020   case EHPersonality::MSVC_CXX: return 16;
16021   default: break;
16022   }
16023   report_fatal_error("can only recover FP for MSVC EH personality functions");
16024 }
16025
16026 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16027 /// function or when returning to a parent frame after catching an exception, we
16028 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16029 /// Here's the math:
16030 ///   RegNodeBase = EntryEBP - RegNodeSize
16031 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
16032 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16033 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16034 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16035                                    SDValue EntryEBP) {
16036   MachineFunction &MF = DAG.getMachineFunction();
16037   SDLoc dl;
16038
16039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16040   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16041
16042   // It's possible that the parent function no longer has a personality function
16043   // if the exceptional code was optimized away, in which case we just return
16044   // the incoming EBP.
16045   if (!Fn->hasPersonalityFn())
16046     return EntryEBP;
16047
16048   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16049
16050   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16051   // registration.
16052   MCSymbol *OffsetSym =
16053       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16054           GlobalValue::getRealLinkageName(Fn->getName()));
16055   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16056   SDValue RegNodeFrameOffset =
16057       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16058
16059   // RegNodeBase = EntryEBP - RegNodeSize
16060   // ParentFP = RegNodeBase - RegNodeFrameOffset
16061   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16062                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16063   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16064 }
16065
16066 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16067                                        SelectionDAG &DAG) {
16068   SDLoc dl(Op);
16069   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16070   MVT VT = Op.getSimpleValueType();
16071   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16072   if (IntrData) {
16073     switch(IntrData->Type) {
16074     case INTR_TYPE_1OP:
16075       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16076     case INTR_TYPE_2OP:
16077       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16078         Op.getOperand(2));
16079     case INTR_TYPE_2OP_IMM8:
16080       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16081                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16082     case INTR_TYPE_3OP:
16083       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16084         Op.getOperand(2), Op.getOperand(3));
16085     case INTR_TYPE_4OP:
16086       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16087         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16088     case INTR_TYPE_1OP_MASK_RM: {
16089       SDValue Src = Op.getOperand(1);
16090       SDValue PassThru = Op.getOperand(2);
16091       SDValue Mask = Op.getOperand(3);
16092       SDValue RoundingMode;
16093       // We allways add rounding mode to the Node.
16094       // If the rounding mode is not specified, we add the
16095       // "current direction" mode.
16096       if (Op.getNumOperands() == 4)
16097         RoundingMode =
16098           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16099       else
16100         RoundingMode = Op.getOperand(4);
16101       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16102       if (IntrWithRoundingModeOpcode != 0)
16103         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16104             X86::STATIC_ROUNDING::CUR_DIRECTION)
16105           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16106                                       dl, Op.getValueType(), Src, RoundingMode),
16107                                       Mask, PassThru, Subtarget, DAG);
16108       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16109                                               RoundingMode),
16110                                   Mask, PassThru, Subtarget, DAG);
16111     }
16112     case INTR_TYPE_1OP_MASK: {
16113       SDValue Src = Op.getOperand(1);
16114       SDValue PassThru = Op.getOperand(2);
16115       SDValue Mask = Op.getOperand(3);
16116       // We add rounding mode to the Node when
16117       //   - RM Opcode is specified and
16118       //   - RM is not "current direction".
16119       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16120       if (IntrWithRoundingModeOpcode != 0) {
16121         SDValue Rnd = Op.getOperand(4);
16122         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16123         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16124           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16125                                       dl, Op.getValueType(),
16126                                       Src, Rnd),
16127                                       Mask, PassThru, Subtarget, DAG);
16128         }
16129       }
16130       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16131                                   Mask, PassThru, Subtarget, DAG);
16132     }
16133     case INTR_TYPE_SCALAR_MASK: {
16134       SDValue Src1 = Op.getOperand(1);
16135       SDValue Src2 = Op.getOperand(2);
16136       SDValue passThru = Op.getOperand(3);
16137       SDValue Mask = Op.getOperand(4);
16138       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16139                                   Mask, passThru, Subtarget, DAG);
16140     }
16141     case INTR_TYPE_SCALAR_MASK_RM: {
16142       SDValue Src1 = Op.getOperand(1);
16143       SDValue Src2 = Op.getOperand(2);
16144       SDValue Src0 = Op.getOperand(3);
16145       SDValue Mask = Op.getOperand(4);
16146       // There are 2 kinds of intrinsics in this group:
16147       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16148       // (2) With rounding mode and sae - 7 operands.
16149       if (Op.getNumOperands() == 6) {
16150         SDValue Sae  = Op.getOperand(5);
16151         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16152         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16153                                                 Sae),
16154                                     Mask, Src0, Subtarget, DAG);
16155       }
16156       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16157       SDValue RoundingMode  = Op.getOperand(5);
16158       SDValue Sae  = Op.getOperand(6);
16159       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16160                                               RoundingMode, Sae),
16161                                   Mask, Src0, Subtarget, DAG);
16162     }
16163     case INTR_TYPE_2OP_MASK:
16164     case INTR_TYPE_2OP_IMM8_MASK: {
16165       SDValue Src1 = Op.getOperand(1);
16166       SDValue Src2 = Op.getOperand(2);
16167       SDValue PassThru = Op.getOperand(3);
16168       SDValue Mask = Op.getOperand(4);
16169
16170       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16171         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16172
16173       // We specify 2 possible opcodes for intrinsics with rounding modes.
16174       // First, we check if the intrinsic may have non-default rounding mode,
16175       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16176       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16177       if (IntrWithRoundingModeOpcode != 0) {
16178         SDValue Rnd = Op.getOperand(5);
16179         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16180         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16181           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16182                                       dl, Op.getValueType(),
16183                                       Src1, Src2, Rnd),
16184                                       Mask, PassThru, Subtarget, DAG);
16185         }
16186       }
16187       // TODO: Intrinsics should have fast-math-flags to propagate.
16188       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16189                                   Mask, PassThru, Subtarget, DAG);
16190     }
16191     case INTR_TYPE_2OP_MASK_RM: {
16192       SDValue Src1 = Op.getOperand(1);
16193       SDValue Src2 = Op.getOperand(2);
16194       SDValue PassThru = Op.getOperand(3);
16195       SDValue Mask = Op.getOperand(4);
16196       // We specify 2 possible modes for intrinsics, with/without rounding
16197       // modes.
16198       // First, we check if the intrinsic have rounding mode (6 operands),
16199       // if not, we set rounding mode to "current".
16200       SDValue Rnd;
16201       if (Op.getNumOperands() == 6)
16202         Rnd = Op.getOperand(5);
16203       else
16204         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16205       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16206                                               Src1, Src2, Rnd),
16207                                   Mask, PassThru, Subtarget, DAG);
16208     }
16209     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16210       SDValue Src1 = Op.getOperand(1);
16211       SDValue Src2 = Op.getOperand(2);
16212       SDValue Src3 = Op.getOperand(3);
16213       SDValue PassThru = Op.getOperand(4);
16214       SDValue Mask = Op.getOperand(5);
16215       SDValue Sae  = Op.getOperand(6);
16216
16217       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16218                                               Src2, Src3, Sae),
16219                                   Mask, PassThru, Subtarget, DAG);
16220     }
16221     case INTR_TYPE_3OP_MASK_RM: {
16222       SDValue Src1 = Op.getOperand(1);
16223       SDValue Src2 = Op.getOperand(2);
16224       SDValue Imm = Op.getOperand(3);
16225       SDValue PassThru = Op.getOperand(4);
16226       SDValue Mask = Op.getOperand(5);
16227       // We specify 2 possible modes for intrinsics, with/without rounding
16228       // modes.
16229       // First, we check if the intrinsic have rounding mode (7 operands),
16230       // if not, we set rounding mode to "current".
16231       SDValue Rnd;
16232       if (Op.getNumOperands() == 7)
16233         Rnd = Op.getOperand(6);
16234       else
16235         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16236       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16237         Src1, Src2, Imm, Rnd),
16238         Mask, PassThru, Subtarget, DAG);
16239     }
16240     case INTR_TYPE_3OP_IMM8_MASK:
16241     case INTR_TYPE_3OP_MASK:
16242     case INSERT_SUBVEC: {
16243       SDValue Src1 = Op.getOperand(1);
16244       SDValue Src2 = Op.getOperand(2);
16245       SDValue Src3 = Op.getOperand(3);
16246       SDValue PassThru = Op.getOperand(4);
16247       SDValue Mask = Op.getOperand(5);
16248
16249       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16250         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16251       else if (IntrData->Type == INSERT_SUBVEC) {
16252         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16253         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16254         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16255         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16256         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16257       }
16258
16259       // We specify 2 possible opcodes for intrinsics with rounding modes.
16260       // First, we check if the intrinsic may have non-default rounding mode,
16261       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16262       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16263       if (IntrWithRoundingModeOpcode != 0) {
16264         SDValue Rnd = Op.getOperand(6);
16265         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16266         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16267           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16268                                       dl, Op.getValueType(),
16269                                       Src1, Src2, Src3, Rnd),
16270                                       Mask, PassThru, Subtarget, DAG);
16271         }
16272       }
16273       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16274                                               Src1, Src2, Src3),
16275                                   Mask, PassThru, Subtarget, DAG);
16276     }
16277     case VPERM_3OP_MASKZ:
16278     case VPERM_3OP_MASK:
16279     case FMA_OP_MASK3:
16280     case FMA_OP_MASKZ:
16281     case FMA_OP_MASK: {
16282       SDValue Src1 = Op.getOperand(1);
16283       SDValue Src2 = Op.getOperand(2);
16284       SDValue Src3 = Op.getOperand(3);
16285       SDValue Mask = Op.getOperand(4);
16286       MVT VT = Op.getSimpleValueType();
16287       SDValue PassThru = SDValue();
16288
16289       // set PassThru element
16290       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16291         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16292       else if (IntrData->Type == FMA_OP_MASK3)
16293         PassThru = Src3;
16294       else
16295         PassThru = Src1;
16296
16297       // We specify 2 possible opcodes for intrinsics with rounding modes.
16298       // First, we check if the intrinsic may have non-default rounding mode,
16299       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16300       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16301       if (IntrWithRoundingModeOpcode != 0) {
16302         SDValue Rnd = Op.getOperand(5);
16303         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16304             X86::STATIC_ROUNDING::CUR_DIRECTION)
16305           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16306                                                   dl, Op.getValueType(),
16307                                                   Src1, Src2, Src3, Rnd),
16308                                       Mask, PassThru, Subtarget, DAG);
16309       }
16310       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16311                                               dl, Op.getValueType(),
16312                                               Src1, Src2, Src3),
16313                                   Mask, PassThru, Subtarget, DAG);
16314     }
16315     case TERLOG_OP_MASK:
16316     case TERLOG_OP_MASKZ: {
16317       SDValue Src1 = Op.getOperand(1);
16318       SDValue Src2 = Op.getOperand(2);
16319       SDValue Src3 = Op.getOperand(3);
16320       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16321       SDValue Mask = Op.getOperand(5);
16322       MVT VT = Op.getSimpleValueType();
16323       SDValue PassThru = Src1;
16324       // Set PassThru element.
16325       if (IntrData->Type == TERLOG_OP_MASKZ)
16326         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16327
16328       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16329                                               Src1, Src2, Src3, Src4),
16330                                   Mask, PassThru, Subtarget, DAG);
16331     }
16332     case FPCLASS: {
16333       // FPclass intrinsics with mask
16334        SDValue Src1 = Op.getOperand(1);
16335        MVT VT = Src1.getSimpleValueType();
16336        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16337        SDValue Imm = Op.getOperand(2);
16338        SDValue Mask = Op.getOperand(3);
16339        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16340                                      Mask.getSimpleValueType().getSizeInBits());
16341        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16342        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16343                                                  DAG.getTargetConstant(0, dl, MaskVT),
16344                                                  Subtarget, DAG);
16345        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16346                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16347                                  DAG.getIntPtrConstant(0, dl));
16348        return DAG.getBitcast(Op.getValueType(), Res);
16349     }
16350     case FPCLASSS: {
16351       SDValue Src1 = Op.getOperand(1);
16352       SDValue Imm = Op.getOperand(2);
16353       SDValue Mask = Op.getOperand(3);
16354       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16355       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16356         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16357       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16358     }
16359     case CMP_MASK:
16360     case CMP_MASK_CC: {
16361       // Comparison intrinsics with masks.
16362       // Example of transformation:
16363       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16364       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16365       // (i8 (bitcast
16366       //   (v8i1 (insert_subvector undef,
16367       //           (v2i1 (and (PCMPEQM %a, %b),
16368       //                      (extract_subvector
16369       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16370       MVT VT = Op.getOperand(1).getSimpleValueType();
16371       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16372       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16373       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16374                                        Mask.getSimpleValueType().getSizeInBits());
16375       SDValue Cmp;
16376       if (IntrData->Type == CMP_MASK_CC) {
16377         SDValue CC = Op.getOperand(3);
16378         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16379         // We specify 2 possible opcodes for intrinsics with rounding modes.
16380         // First, we check if the intrinsic may have non-default rounding mode,
16381         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16382         if (IntrData->Opc1 != 0) {
16383           SDValue Rnd = Op.getOperand(5);
16384           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16385               X86::STATIC_ROUNDING::CUR_DIRECTION)
16386             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16387                               Op.getOperand(2), CC, Rnd);
16388         }
16389         //default rounding mode
16390         if(!Cmp.getNode())
16391             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16392                               Op.getOperand(2), CC);
16393
16394       } else {
16395         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16396         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16397                           Op.getOperand(2));
16398       }
16399       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16400                                              DAG.getTargetConstant(0, dl,
16401                                                                    MaskVT),
16402                                              Subtarget, DAG);
16403       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16404                                 DAG.getUNDEF(BitcastVT), CmpMask,
16405                                 DAG.getIntPtrConstant(0, dl));
16406       return DAG.getBitcast(Op.getValueType(), Res);
16407     }
16408     case CMP_MASK_SCALAR_CC: {
16409       SDValue Src1 = Op.getOperand(1);
16410       SDValue Src2 = Op.getOperand(2);
16411       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16412       SDValue Mask = Op.getOperand(4);
16413
16414       SDValue Cmp;
16415       if (IntrData->Opc1 != 0) {
16416         SDValue Rnd = Op.getOperand(5);
16417         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16418             X86::STATIC_ROUNDING::CUR_DIRECTION)
16419           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16420       }
16421       //default rounding mode
16422       if(!Cmp.getNode())
16423         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16424
16425       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16426                                              DAG.getTargetConstant(0, dl,
16427                                                                    MVT::i1),
16428                                              Subtarget, DAG);
16429
16430       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16431                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16432                          DAG.getValueType(MVT::i1));
16433     }
16434     case COMI: { // Comparison intrinsics
16435       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16436       SDValue LHS = Op.getOperand(1);
16437       SDValue RHS = Op.getOperand(2);
16438       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16439       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16440       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16441       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16442                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16443       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16444     }
16445     case VSHIFT:
16446       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16447                                  Op.getOperand(1), Op.getOperand(2), DAG);
16448     case VSHIFT_MASK:
16449       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16450                                                       Op.getSimpleValueType(),
16451                                                       Op.getOperand(1),
16452                                                       Op.getOperand(2), DAG),
16453                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16454                                   DAG);
16455     case COMPRESS_EXPAND_IN_REG: {
16456       SDValue Mask = Op.getOperand(3);
16457       SDValue DataToCompress = Op.getOperand(1);
16458       SDValue PassThru = Op.getOperand(2);
16459       if (isAllOnes(Mask)) // return data as is
16460         return Op.getOperand(1);
16461
16462       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16463                                               DataToCompress),
16464                                   Mask, PassThru, Subtarget, DAG);
16465     }
16466     case BROADCASTM: {
16467       SDValue Mask = Op.getOperand(1);
16468       MVT MaskVT = MVT::getVectorVT(MVT::i1, Mask.getSimpleValueType().getSizeInBits());
16469       Mask = DAG.getBitcast(MaskVT, Mask);
16470       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16471     }
16472     case BLEND: {
16473       SDValue Mask = Op.getOperand(3);
16474       MVT VT = Op.getSimpleValueType();
16475       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16476       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16477                                        Mask.getSimpleValueType().getSizeInBits());
16478       SDLoc dl(Op);
16479       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16480                                   DAG.getBitcast(BitcastVT, Mask),
16481                                   DAG.getIntPtrConstant(0, dl));
16482       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16483                          Op.getOperand(2));
16484     }
16485     default:
16486       break;
16487     }
16488   }
16489
16490   switch (IntNo) {
16491   default: return SDValue();    // Don't custom lower most intrinsics.
16492
16493   case Intrinsic::x86_avx2_permd:
16494   case Intrinsic::x86_avx2_permps:
16495     // Operands intentionally swapped. Mask is last operand to intrinsic,
16496     // but second operand for node/instruction.
16497     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16498                        Op.getOperand(2), Op.getOperand(1));
16499
16500   // ptest and testp intrinsics. The intrinsic these come from are designed to
16501   // return an integer value, not just an instruction so lower it to the ptest
16502   // or testp pattern and a setcc for the result.
16503   case Intrinsic::x86_sse41_ptestz:
16504   case Intrinsic::x86_sse41_ptestc:
16505   case Intrinsic::x86_sse41_ptestnzc:
16506   case Intrinsic::x86_avx_ptestz_256:
16507   case Intrinsic::x86_avx_ptestc_256:
16508   case Intrinsic::x86_avx_ptestnzc_256:
16509   case Intrinsic::x86_avx_vtestz_ps:
16510   case Intrinsic::x86_avx_vtestc_ps:
16511   case Intrinsic::x86_avx_vtestnzc_ps:
16512   case Intrinsic::x86_avx_vtestz_pd:
16513   case Intrinsic::x86_avx_vtestc_pd:
16514   case Intrinsic::x86_avx_vtestnzc_pd:
16515   case Intrinsic::x86_avx_vtestz_ps_256:
16516   case Intrinsic::x86_avx_vtestc_ps_256:
16517   case Intrinsic::x86_avx_vtestnzc_ps_256:
16518   case Intrinsic::x86_avx_vtestz_pd_256:
16519   case Intrinsic::x86_avx_vtestc_pd_256:
16520   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16521     bool IsTestPacked = false;
16522     unsigned X86CC;
16523     switch (IntNo) {
16524     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16525     case Intrinsic::x86_avx_vtestz_ps:
16526     case Intrinsic::x86_avx_vtestz_pd:
16527     case Intrinsic::x86_avx_vtestz_ps_256:
16528     case Intrinsic::x86_avx_vtestz_pd_256:
16529       IsTestPacked = true; // Fallthrough
16530     case Intrinsic::x86_sse41_ptestz:
16531     case Intrinsic::x86_avx_ptestz_256:
16532       // ZF = 1
16533       X86CC = X86::COND_E;
16534       break;
16535     case Intrinsic::x86_avx_vtestc_ps:
16536     case Intrinsic::x86_avx_vtestc_pd:
16537     case Intrinsic::x86_avx_vtestc_ps_256:
16538     case Intrinsic::x86_avx_vtestc_pd_256:
16539       IsTestPacked = true; // Fallthrough
16540     case Intrinsic::x86_sse41_ptestc:
16541     case Intrinsic::x86_avx_ptestc_256:
16542       // CF = 1
16543       X86CC = X86::COND_B;
16544       break;
16545     case Intrinsic::x86_avx_vtestnzc_ps:
16546     case Intrinsic::x86_avx_vtestnzc_pd:
16547     case Intrinsic::x86_avx_vtestnzc_ps_256:
16548     case Intrinsic::x86_avx_vtestnzc_pd_256:
16549       IsTestPacked = true; // Fallthrough
16550     case Intrinsic::x86_sse41_ptestnzc:
16551     case Intrinsic::x86_avx_ptestnzc_256:
16552       // ZF and CF = 0
16553       X86CC = X86::COND_A;
16554       break;
16555     }
16556
16557     SDValue LHS = Op.getOperand(1);
16558     SDValue RHS = Op.getOperand(2);
16559     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16560     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16561     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16562     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16563     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16564   }
16565   case Intrinsic::x86_avx512_kortestz_w:
16566   case Intrinsic::x86_avx512_kortestc_w: {
16567     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16568     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16569     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16570     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16571     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16572     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16573     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16574   }
16575
16576   case Intrinsic::x86_sse42_pcmpistria128:
16577   case Intrinsic::x86_sse42_pcmpestria128:
16578   case Intrinsic::x86_sse42_pcmpistric128:
16579   case Intrinsic::x86_sse42_pcmpestric128:
16580   case Intrinsic::x86_sse42_pcmpistrio128:
16581   case Intrinsic::x86_sse42_pcmpestrio128:
16582   case Intrinsic::x86_sse42_pcmpistris128:
16583   case Intrinsic::x86_sse42_pcmpestris128:
16584   case Intrinsic::x86_sse42_pcmpistriz128:
16585   case Intrinsic::x86_sse42_pcmpestriz128: {
16586     unsigned Opcode;
16587     unsigned X86CC;
16588     switch (IntNo) {
16589     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16590     case Intrinsic::x86_sse42_pcmpistria128:
16591       Opcode = X86ISD::PCMPISTRI;
16592       X86CC = X86::COND_A;
16593       break;
16594     case Intrinsic::x86_sse42_pcmpestria128:
16595       Opcode = X86ISD::PCMPESTRI;
16596       X86CC = X86::COND_A;
16597       break;
16598     case Intrinsic::x86_sse42_pcmpistric128:
16599       Opcode = X86ISD::PCMPISTRI;
16600       X86CC = X86::COND_B;
16601       break;
16602     case Intrinsic::x86_sse42_pcmpestric128:
16603       Opcode = X86ISD::PCMPESTRI;
16604       X86CC = X86::COND_B;
16605       break;
16606     case Intrinsic::x86_sse42_pcmpistrio128:
16607       Opcode = X86ISD::PCMPISTRI;
16608       X86CC = X86::COND_O;
16609       break;
16610     case Intrinsic::x86_sse42_pcmpestrio128:
16611       Opcode = X86ISD::PCMPESTRI;
16612       X86CC = X86::COND_O;
16613       break;
16614     case Intrinsic::x86_sse42_pcmpistris128:
16615       Opcode = X86ISD::PCMPISTRI;
16616       X86CC = X86::COND_S;
16617       break;
16618     case Intrinsic::x86_sse42_pcmpestris128:
16619       Opcode = X86ISD::PCMPESTRI;
16620       X86CC = X86::COND_S;
16621       break;
16622     case Intrinsic::x86_sse42_pcmpistriz128:
16623       Opcode = X86ISD::PCMPISTRI;
16624       X86CC = X86::COND_E;
16625       break;
16626     case Intrinsic::x86_sse42_pcmpestriz128:
16627       Opcode = X86ISD::PCMPESTRI;
16628       X86CC = X86::COND_E;
16629       break;
16630     }
16631     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16632     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16633     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16634     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16635                                 DAG.getConstant(X86CC, dl, MVT::i8),
16636                                 SDValue(PCMP.getNode(), 1));
16637     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16638   }
16639
16640   case Intrinsic::x86_sse42_pcmpistri128:
16641   case Intrinsic::x86_sse42_pcmpestri128: {
16642     unsigned Opcode;
16643     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16644       Opcode = X86ISD::PCMPISTRI;
16645     else
16646       Opcode = X86ISD::PCMPESTRI;
16647
16648     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16649     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16650     return DAG.getNode(Opcode, dl, VTs, NewOps);
16651   }
16652
16653   case Intrinsic::x86_seh_lsda: {
16654     // Compute the symbol for the LSDA. We know it'll get emitted later.
16655     MachineFunction &MF = DAG.getMachineFunction();
16656     SDValue Op1 = Op.getOperand(1);
16657     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16658     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16659         GlobalValue::getRealLinkageName(Fn->getName()));
16660
16661     // Generate a simple absolute symbol reference. This intrinsic is only
16662     // supported on 32-bit Windows, which isn't PIC.
16663     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16664     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16665   }
16666
16667   case Intrinsic::x86_seh_recoverfp: {
16668     SDValue FnOp = Op.getOperand(1);
16669     SDValue IncomingFPOp = Op.getOperand(2);
16670     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16671     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16672     if (!Fn)
16673       report_fatal_error(
16674           "llvm.x86.seh.recoverfp must take a function as the first argument");
16675     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16676   }
16677
16678   case Intrinsic::localaddress: {
16679     // Returns one of the stack, base, or frame pointer registers, depending on
16680     // which is used to reference local variables.
16681     MachineFunction &MF = DAG.getMachineFunction();
16682     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16683     unsigned Reg;
16684     if (RegInfo->hasBasePointer(MF))
16685       Reg = RegInfo->getBaseRegister();
16686     else // This function handles the SP or FP case.
16687       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16688     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16689   }
16690   }
16691 }
16692
16693 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16694                               SDValue Src, SDValue Mask, SDValue Base,
16695                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16696                               const X86Subtarget * Subtarget) {
16697   SDLoc dl(Op);
16698   auto *C = cast<ConstantSDNode>(ScaleOp);
16699   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16700   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16701                              Index.getSimpleValueType().getVectorNumElements());
16702   SDValue MaskInReg;
16703   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16704   if (MaskC)
16705     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16706   else {
16707     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16708                                      Mask.getSimpleValueType().getSizeInBits());
16709
16710     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16711     // are extracted by EXTRACT_SUBVECTOR.
16712     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16713                             DAG.getBitcast(BitcastVT, Mask),
16714                             DAG.getIntPtrConstant(0, dl));
16715   }
16716   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16717   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16718   SDValue Segment = DAG.getRegister(0, MVT::i32);
16719   if (Src.getOpcode() == ISD::UNDEF)
16720     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16721   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16722   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16723   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16724   return DAG.getMergeValues(RetOps, dl);
16725 }
16726
16727 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16728                                SDValue Src, SDValue Mask, SDValue Base,
16729                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16730   SDLoc dl(Op);
16731   auto *C = cast<ConstantSDNode>(ScaleOp);
16732   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16733   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16734   SDValue Segment = DAG.getRegister(0, MVT::i32);
16735   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16736                              Index.getSimpleValueType().getVectorNumElements());
16737   SDValue MaskInReg;
16738   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16739   if (MaskC)
16740     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16741   else {
16742     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16743                                      Mask.getSimpleValueType().getSizeInBits());
16744
16745     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16746     // are extracted by EXTRACT_SUBVECTOR.
16747     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16748                             DAG.getBitcast(BitcastVT, Mask),
16749                             DAG.getIntPtrConstant(0, dl));
16750   }
16751   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16752   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16753   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16754   return SDValue(Res, 1);
16755 }
16756
16757 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16758                                SDValue Mask, SDValue Base, SDValue Index,
16759                                SDValue ScaleOp, SDValue Chain) {
16760   SDLoc dl(Op);
16761   auto *C = cast<ConstantSDNode>(ScaleOp);
16762   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16763   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16764   SDValue Segment = DAG.getRegister(0, MVT::i32);
16765   MVT MaskVT =
16766     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16767   SDValue MaskInReg;
16768   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16769   if (MaskC)
16770     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16771   else
16772     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16773   //SDVTList VTs = DAG.getVTList(MVT::Other);
16774   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16775   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16776   return SDValue(Res, 0);
16777 }
16778
16779 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16780 // read performance monitor counters (x86_rdpmc).
16781 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16782                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16783                               SmallVectorImpl<SDValue> &Results) {
16784   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16785   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16786   SDValue LO, HI;
16787
16788   // The ECX register is used to select the index of the performance counter
16789   // to read.
16790   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16791                                    N->getOperand(2));
16792   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16793
16794   // Reads the content of a 64-bit performance counter and returns it in the
16795   // registers EDX:EAX.
16796   if (Subtarget->is64Bit()) {
16797     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16798     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16799                             LO.getValue(2));
16800   } else {
16801     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16802     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16803                             LO.getValue(2));
16804   }
16805   Chain = HI.getValue(1);
16806
16807   if (Subtarget->is64Bit()) {
16808     // The EAX register is loaded with the low-order 32 bits. The EDX register
16809     // is loaded with the supported high-order bits of the counter.
16810     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16811                               DAG.getConstant(32, DL, MVT::i8));
16812     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16813     Results.push_back(Chain);
16814     return;
16815   }
16816
16817   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16818   SDValue Ops[] = { LO, HI };
16819   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16820   Results.push_back(Pair);
16821   Results.push_back(Chain);
16822 }
16823
16824 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16825 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16826 // also used to custom lower READCYCLECOUNTER nodes.
16827 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16828                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16829                               SmallVectorImpl<SDValue> &Results) {
16830   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16831   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16832   SDValue LO, HI;
16833
16834   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16835   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16836   // and the EAX register is loaded with the low-order 32 bits.
16837   if (Subtarget->is64Bit()) {
16838     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16839     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16840                             LO.getValue(2));
16841   } else {
16842     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16843     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16844                             LO.getValue(2));
16845   }
16846   SDValue Chain = HI.getValue(1);
16847
16848   if (Opcode == X86ISD::RDTSCP_DAG) {
16849     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16850
16851     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16852     // the ECX register. Add 'ecx' explicitly to the chain.
16853     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16854                                      HI.getValue(2));
16855     // Explicitly store the content of ECX at the location passed in input
16856     // to the 'rdtscp' intrinsic.
16857     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16858                          MachinePointerInfo(), false, false, 0);
16859   }
16860
16861   if (Subtarget->is64Bit()) {
16862     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16863     // the EAX register is loaded with the low-order 32 bits.
16864     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16865                               DAG.getConstant(32, DL, MVT::i8));
16866     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16867     Results.push_back(Chain);
16868     return;
16869   }
16870
16871   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16872   SDValue Ops[] = { LO, HI };
16873   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16874   Results.push_back(Pair);
16875   Results.push_back(Chain);
16876 }
16877
16878 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16879                                      SelectionDAG &DAG) {
16880   SmallVector<SDValue, 2> Results;
16881   SDLoc DL(Op);
16882   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16883                           Results);
16884   return DAG.getMergeValues(Results, DL);
16885 }
16886
16887 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16888                                     SelectionDAG &DAG) {
16889   MachineFunction &MF = DAG.getMachineFunction();
16890   const Function *Fn = MF.getFunction();
16891   SDLoc dl(Op);
16892   SDValue Chain = Op.getOperand(0);
16893
16894   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16895          "using llvm.x86.seh.restoreframe requires a frame pointer");
16896
16897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16898   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16899
16900   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16901   unsigned FrameReg =
16902       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16903   unsigned SPReg = RegInfo->getStackRegister();
16904   unsigned SlotSize = RegInfo->getSlotSize();
16905
16906   // Get incoming EBP.
16907   SDValue IncomingEBP =
16908       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16909
16910   // SP is saved in the first field of every registration node, so load
16911   // [EBP-RegNodeSize] into SP.
16912   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16913   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16914                                DAG.getConstant(-RegNodeSize, dl, VT));
16915   SDValue NewSP =
16916       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16917                   false, VT.getScalarSizeInBits() / 8);
16918   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16919
16920   if (!RegInfo->needsStackRealignment(MF)) {
16921     // Adjust EBP to point back to the original frame position.
16922     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16923     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16924   } else {
16925     assert(RegInfo->hasBasePointer(MF) &&
16926            "functions with Win32 EH must use frame or base pointer register");
16927
16928     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16929     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16930     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16931
16932     // Reload the spilled EBP value, now that the stack and base pointers are
16933     // set up.
16934     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16935     X86FI->setHasSEHFramePtrSave(true);
16936     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16937     X86FI->setSEHFramePtrSaveIndex(FI);
16938     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16939                                 MachinePointerInfo(), false, false, false,
16940                                 VT.getScalarSizeInBits() / 8);
16941     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16942   }
16943
16944   return Chain;
16945 }
16946
16947 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
16948   MachineFunction &MF = DAG.getMachineFunction();
16949   SDValue Chain = Op.getOperand(0);
16950   SDValue RegNode = Op.getOperand(2);
16951   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
16952   if (!EHInfo)
16953     report_fatal_error("EH registrations only live in functions using WinEH");
16954
16955   // Cast the operand to an alloca, and remember the frame index.
16956   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
16957   if (!FINode)
16958     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
16959   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
16960
16961   // Return the chain operand without making any DAG nodes.
16962   return Chain;
16963 }
16964
16965 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16966 /// return truncate Store/MaskedStore Node
16967 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16968                                                SelectionDAG &DAG,
16969                                                MVT ElementType) {
16970   SDLoc dl(Op);
16971   SDValue Mask = Op.getOperand(4);
16972   SDValue DataToTruncate = Op.getOperand(3);
16973   SDValue Addr = Op.getOperand(2);
16974   SDValue Chain = Op.getOperand(0);
16975
16976   MVT VT  = DataToTruncate.getSimpleValueType();
16977   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
16978
16979   if (isAllOnes(Mask)) // return just a truncate store
16980     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16981                              MachinePointerInfo(), SVT, false, false,
16982                              SVT.getScalarSizeInBits()/8);
16983
16984   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16985   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16986                                    Mask.getSimpleValueType().getSizeInBits());
16987   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16988   // are extracted by EXTRACT_SUBVECTOR.
16989   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16990                               DAG.getBitcast(BitcastVT, Mask),
16991                               DAG.getIntPtrConstant(0, dl));
16992
16993   MachineMemOperand *MMO = DAG.getMachineFunction().
16994     getMachineMemOperand(MachinePointerInfo(),
16995                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16996                          SVT.getScalarSizeInBits()/8);
16997
16998   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16999                             VMask, SVT, MMO, true);
17000 }
17001
17002 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17003                                       SelectionDAG &DAG) {
17004   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17005
17006   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17007   if (!IntrData) {
17008     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
17009       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
17010     else if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17011       return MarkEHRegistrationNode(Op, DAG);
17012     return SDValue();
17013   }
17014
17015   SDLoc dl(Op);
17016   switch(IntrData->Type) {
17017   default: llvm_unreachable("Unknown Intrinsic Type");
17018   case RDSEED:
17019   case RDRAND: {
17020     // Emit the node with the right value type.
17021     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17022     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17023
17024     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17025     // Otherwise return the value from Rand, which is always 0, casted to i32.
17026     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17027                       DAG.getConstant(1, dl, Op->getValueType(1)),
17028                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17029                       SDValue(Result.getNode(), 1) };
17030     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17031                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17032                                   Ops);
17033
17034     // Return { result, isValid, chain }.
17035     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17036                        SDValue(Result.getNode(), 2));
17037   }
17038   case GATHER: {
17039   //gather(v1, mask, index, base, scale);
17040     SDValue Chain = Op.getOperand(0);
17041     SDValue Src   = Op.getOperand(2);
17042     SDValue Base  = Op.getOperand(3);
17043     SDValue Index = Op.getOperand(4);
17044     SDValue Mask  = Op.getOperand(5);
17045     SDValue Scale = Op.getOperand(6);
17046     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17047                          Chain, Subtarget);
17048   }
17049   case SCATTER: {
17050   //scatter(base, mask, index, v1, scale);
17051     SDValue Chain = Op.getOperand(0);
17052     SDValue Base  = Op.getOperand(2);
17053     SDValue Mask  = Op.getOperand(3);
17054     SDValue Index = Op.getOperand(4);
17055     SDValue Src   = Op.getOperand(5);
17056     SDValue Scale = Op.getOperand(6);
17057     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17058                           Scale, Chain);
17059   }
17060   case PREFETCH: {
17061     SDValue Hint = Op.getOperand(6);
17062     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17063     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17064     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17065     SDValue Chain = Op.getOperand(0);
17066     SDValue Mask  = Op.getOperand(2);
17067     SDValue Index = Op.getOperand(3);
17068     SDValue Base  = Op.getOperand(4);
17069     SDValue Scale = Op.getOperand(5);
17070     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17071   }
17072   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17073   case RDTSC: {
17074     SmallVector<SDValue, 2> Results;
17075     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17076                             Results);
17077     return DAG.getMergeValues(Results, dl);
17078   }
17079   // Read Performance Monitoring Counters.
17080   case RDPMC: {
17081     SmallVector<SDValue, 2> Results;
17082     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17083     return DAG.getMergeValues(Results, dl);
17084   }
17085   // XTEST intrinsics.
17086   case XTEST: {
17087     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17088     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17089     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17090                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17091                                 InTrans);
17092     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17093     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17094                        Ret, SDValue(InTrans.getNode(), 1));
17095   }
17096   // ADC/ADCX/SBB
17097   case ADX: {
17098     SmallVector<SDValue, 2> Results;
17099     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17100     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17101     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17102                                 DAG.getConstant(-1, dl, MVT::i8));
17103     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17104                               Op.getOperand(4), GenCF.getValue(1));
17105     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17106                                  Op.getOperand(5), MachinePointerInfo(),
17107                                  false, false, 0);
17108     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17109                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17110                                 Res.getValue(1));
17111     Results.push_back(SetCC);
17112     Results.push_back(Store);
17113     return DAG.getMergeValues(Results, dl);
17114   }
17115   case COMPRESS_TO_MEM: {
17116     SDLoc dl(Op);
17117     SDValue Mask = Op.getOperand(4);
17118     SDValue DataToCompress = Op.getOperand(3);
17119     SDValue Addr = Op.getOperand(2);
17120     SDValue Chain = Op.getOperand(0);
17121
17122     MVT VT = DataToCompress.getSimpleValueType();
17123     if (isAllOnes(Mask)) // return just a store
17124       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17125                           MachinePointerInfo(), false, false,
17126                           VT.getScalarSizeInBits()/8);
17127
17128     SDValue Compressed =
17129       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17130                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17131     return DAG.getStore(Chain, dl, Compressed, Addr,
17132                         MachinePointerInfo(), false, false,
17133                         VT.getScalarSizeInBits()/8);
17134   }
17135   case TRUNCATE_TO_MEM_VI8:
17136     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17137   case TRUNCATE_TO_MEM_VI16:
17138     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17139   case TRUNCATE_TO_MEM_VI32:
17140     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17141   case EXPAND_FROM_MEM: {
17142     SDLoc dl(Op);
17143     SDValue Mask = Op.getOperand(4);
17144     SDValue PassThru = Op.getOperand(3);
17145     SDValue Addr = Op.getOperand(2);
17146     SDValue Chain = Op.getOperand(0);
17147     MVT VT = Op.getSimpleValueType();
17148
17149     if (isAllOnes(Mask)) // return just a load
17150       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17151                          false, VT.getScalarSizeInBits()/8);
17152
17153     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17154                                        false, false, false,
17155                                        VT.getScalarSizeInBits()/8);
17156
17157     SDValue Results[] = {
17158       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17159                            Mask, PassThru, Subtarget, DAG), Chain};
17160     return DAG.getMergeValues(Results, dl);
17161   }
17162   }
17163 }
17164
17165 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17166                                            SelectionDAG &DAG) const {
17167   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17168   MFI->setReturnAddressIsTaken(true);
17169
17170   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17171     return SDValue();
17172
17173   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17174   SDLoc dl(Op);
17175   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17176
17177   if (Depth > 0) {
17178     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17179     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17180     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17181     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17182                        DAG.getNode(ISD::ADD, dl, PtrVT,
17183                                    FrameAddr, Offset),
17184                        MachinePointerInfo(), false, false, false, 0);
17185   }
17186
17187   // Just load the return address.
17188   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17189   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17190                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17191 }
17192
17193 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17194   MachineFunction &MF = DAG.getMachineFunction();
17195   MachineFrameInfo *MFI = MF.getFrameInfo();
17196   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17197   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17198   EVT VT = Op.getValueType();
17199
17200   MFI->setFrameAddressIsTaken(true);
17201
17202   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17203     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17204     // is not possible to crawl up the stack without looking at the unwind codes
17205     // simultaneously.
17206     int FrameAddrIndex = FuncInfo->getFAIndex();
17207     if (!FrameAddrIndex) {
17208       // Set up a frame object for the return address.
17209       unsigned SlotSize = RegInfo->getSlotSize();
17210       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17211           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17212       FuncInfo->setFAIndex(FrameAddrIndex);
17213     }
17214     return DAG.getFrameIndex(FrameAddrIndex, VT);
17215   }
17216
17217   unsigned FrameReg =
17218       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17219   SDLoc dl(Op);  // FIXME probably not meaningful
17220   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17221   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17222           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17223          "Invalid Frame Register!");
17224   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17225   while (Depth--)
17226     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17227                             MachinePointerInfo(),
17228                             false, false, false, 0);
17229   return FrameAddr;
17230 }
17231
17232 // FIXME? Maybe this could be a TableGen attribute on some registers and
17233 // this table could be generated automatically from RegInfo.
17234 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17235                                               SelectionDAG &DAG) const {
17236   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17237   const MachineFunction &MF = DAG.getMachineFunction();
17238
17239   unsigned Reg = StringSwitch<unsigned>(RegName)
17240                        .Case("esp", X86::ESP)
17241                        .Case("rsp", X86::RSP)
17242                        .Case("ebp", X86::EBP)
17243                        .Case("rbp", X86::RBP)
17244                        .Default(0);
17245
17246   if (Reg == X86::EBP || Reg == X86::RBP) {
17247     if (!TFI.hasFP(MF))
17248       report_fatal_error("register " + StringRef(RegName) +
17249                          " is allocatable: function has no frame pointer");
17250 #ifndef NDEBUG
17251     else {
17252       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17253       unsigned FrameReg =
17254           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17255       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17256              "Invalid Frame Register!");
17257     }
17258 #endif
17259   }
17260
17261   if (Reg)
17262     return Reg;
17263
17264   report_fatal_error("Invalid register name global variable");
17265 }
17266
17267 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17268                                                      SelectionDAG &DAG) const {
17269   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17270   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17271 }
17272
17273 unsigned X86TargetLowering::getExceptionPointerRegister(
17274     const Constant *PersonalityFn) const {
17275   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17276     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17277
17278   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17279 }
17280
17281 unsigned X86TargetLowering::getExceptionSelectorRegister(
17282     const Constant *PersonalityFn) const {
17283   // Funclet personalities don't use selectors (the runtime does the selection).
17284   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17285   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17286 }
17287
17288 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17289   SDValue Chain     = Op.getOperand(0);
17290   SDValue Offset    = Op.getOperand(1);
17291   SDValue Handler   = Op.getOperand(2);
17292   SDLoc dl      (Op);
17293
17294   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17295   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17296   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17297   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17298           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17299          "Invalid Frame Register!");
17300   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17301   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17302
17303   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17304                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17305                                                        dl));
17306   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17307   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17308                        false, false, 0);
17309   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17310
17311   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17312                      DAG.getRegister(StoreAddrReg, PtrVT));
17313 }
17314
17315 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17316                                                SelectionDAG &DAG) const {
17317   SDLoc DL(Op);
17318   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17319                      DAG.getVTList(MVT::i32, MVT::Other),
17320                      Op.getOperand(0), Op.getOperand(1));
17321 }
17322
17323 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17324                                                 SelectionDAG &DAG) const {
17325   SDLoc DL(Op);
17326   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17327                      Op.getOperand(0), Op.getOperand(1));
17328 }
17329
17330 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17331   return Op.getOperand(0);
17332 }
17333
17334 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17335                                                 SelectionDAG &DAG) const {
17336   SDValue Root = Op.getOperand(0);
17337   SDValue Trmp = Op.getOperand(1); // trampoline
17338   SDValue FPtr = Op.getOperand(2); // nested function
17339   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17340   SDLoc dl (Op);
17341
17342   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17343   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17344
17345   if (Subtarget->is64Bit()) {
17346     SDValue OutChains[6];
17347
17348     // Large code-model.
17349     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17350     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17351
17352     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17353     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17354
17355     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17356
17357     // Load the pointer to the nested function into R11.
17358     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17359     SDValue Addr = Trmp;
17360     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17361                                 Addr, MachinePointerInfo(TrmpAddr),
17362                                 false, false, 0);
17363
17364     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17365                        DAG.getConstant(2, dl, MVT::i64));
17366     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17367                                 MachinePointerInfo(TrmpAddr, 2),
17368                                 false, false, 2);
17369
17370     // Load the 'nest' parameter value into R10.
17371     // R10 is specified in X86CallingConv.td
17372     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17373     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17374                        DAG.getConstant(10, dl, MVT::i64));
17375     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17376                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17377                                 false, false, 0);
17378
17379     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17380                        DAG.getConstant(12, dl, MVT::i64));
17381     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17382                                 MachinePointerInfo(TrmpAddr, 12),
17383                                 false, false, 2);
17384
17385     // Jump to the nested function.
17386     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17387     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17388                        DAG.getConstant(20, dl, MVT::i64));
17389     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17390                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17391                                 false, false, 0);
17392
17393     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17394     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17395                        DAG.getConstant(22, dl, MVT::i64));
17396     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17397                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17398                                 false, false, 0);
17399
17400     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17401   } else {
17402     const Function *Func =
17403       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17404     CallingConv::ID CC = Func->getCallingConv();
17405     unsigned NestReg;
17406
17407     switch (CC) {
17408     default:
17409       llvm_unreachable("Unsupported calling convention");
17410     case CallingConv::C:
17411     case CallingConv::X86_StdCall: {
17412       // Pass 'nest' parameter in ECX.
17413       // Must be kept in sync with X86CallingConv.td
17414       NestReg = X86::ECX;
17415
17416       // Check that ECX wasn't needed by an 'inreg' parameter.
17417       FunctionType *FTy = Func->getFunctionType();
17418       const AttributeSet &Attrs = Func->getAttributes();
17419
17420       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17421         unsigned InRegCount = 0;
17422         unsigned Idx = 1;
17423
17424         for (FunctionType::param_iterator I = FTy->param_begin(),
17425              E = FTy->param_end(); I != E; ++I, ++Idx)
17426           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17427             auto &DL = DAG.getDataLayout();
17428             // FIXME: should only count parameters that are lowered to integers.
17429             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17430           }
17431
17432         if (InRegCount > 2) {
17433           report_fatal_error("Nest register in use - reduce number of inreg"
17434                              " parameters!");
17435         }
17436       }
17437       break;
17438     }
17439     case CallingConv::X86_FastCall:
17440     case CallingConv::X86_ThisCall:
17441     case CallingConv::Fast:
17442       // Pass 'nest' parameter in EAX.
17443       // Must be kept in sync with X86CallingConv.td
17444       NestReg = X86::EAX;
17445       break;
17446     }
17447
17448     SDValue OutChains[4];
17449     SDValue Addr, Disp;
17450
17451     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17452                        DAG.getConstant(10, dl, MVT::i32));
17453     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17454
17455     // This is storing the opcode for MOV32ri.
17456     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17457     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17458     OutChains[0] = DAG.getStore(Root, dl,
17459                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17460                                 Trmp, MachinePointerInfo(TrmpAddr),
17461                                 false, false, 0);
17462
17463     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17464                        DAG.getConstant(1, dl, MVT::i32));
17465     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17466                                 MachinePointerInfo(TrmpAddr, 1),
17467                                 false, false, 1);
17468
17469     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17470     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17471                        DAG.getConstant(5, dl, MVT::i32));
17472     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17473                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17474                                 false, false, 1);
17475
17476     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17477                        DAG.getConstant(6, dl, MVT::i32));
17478     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17479                                 MachinePointerInfo(TrmpAddr, 6),
17480                                 false, false, 1);
17481
17482     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17483   }
17484 }
17485
17486 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17487                                             SelectionDAG &DAG) const {
17488   /*
17489    The rounding mode is in bits 11:10 of FPSR, and has the following
17490    settings:
17491      00 Round to nearest
17492      01 Round to -inf
17493      10 Round to +inf
17494      11 Round to 0
17495
17496   FLT_ROUNDS, on the other hand, expects the following:
17497     -1 Undefined
17498      0 Round to 0
17499      1 Round to nearest
17500      2 Round to +inf
17501      3 Round to -inf
17502
17503   To perform the conversion, we do:
17504     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17505   */
17506
17507   MachineFunction &MF = DAG.getMachineFunction();
17508   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17509   unsigned StackAlignment = TFI.getStackAlignment();
17510   MVT VT = Op.getSimpleValueType();
17511   SDLoc DL(Op);
17512
17513   // Save FP Control Word to stack slot
17514   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17515   SDValue StackSlot =
17516       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17517
17518   MachineMemOperand *MMO =
17519       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17520                               MachineMemOperand::MOStore, 2, 2);
17521
17522   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17523   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17524                                           DAG.getVTList(MVT::Other),
17525                                           Ops, MVT::i16, MMO);
17526
17527   // Load FP Control Word from stack slot
17528   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17529                             MachinePointerInfo(), false, false, false, 0);
17530
17531   // Transform as necessary
17532   SDValue CWD1 =
17533     DAG.getNode(ISD::SRL, DL, MVT::i16,
17534                 DAG.getNode(ISD::AND, DL, MVT::i16,
17535                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17536                 DAG.getConstant(11, DL, MVT::i8));
17537   SDValue CWD2 =
17538     DAG.getNode(ISD::SRL, DL, MVT::i16,
17539                 DAG.getNode(ISD::AND, DL, MVT::i16,
17540                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17541                 DAG.getConstant(9, DL, MVT::i8));
17542
17543   SDValue RetVal =
17544     DAG.getNode(ISD::AND, DL, MVT::i16,
17545                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17546                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17547                             DAG.getConstant(1, DL, MVT::i16)),
17548                 DAG.getConstant(3, DL, MVT::i16));
17549
17550   return DAG.getNode((VT.getSizeInBits() < 16 ?
17551                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17552 }
17553
17554 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17555 //
17556 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17557 //    to 512-bit vector.
17558 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17559 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17560 //    split the vector, perform operation on it's Lo a Hi part and
17561 //    concatenate the results.
17562 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17563   SDLoc dl(Op);
17564   MVT VT = Op.getSimpleValueType();
17565   MVT EltVT = VT.getVectorElementType();
17566   unsigned NumElems = VT.getVectorNumElements();
17567
17568   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17569     // Extend to 512 bit vector.
17570     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17571               "Unsupported value type for operation");
17572
17573     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17574     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17575                                  DAG.getUNDEF(NewVT),
17576                                  Op.getOperand(0),
17577                                  DAG.getIntPtrConstant(0, dl));
17578     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17579
17580     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17581                        DAG.getIntPtrConstant(0, dl));
17582   }
17583
17584   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17585           "Unsupported element type");
17586
17587   if (16 < NumElems) {
17588     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17589     SDValue Lo, Hi;
17590     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17591     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17592
17593     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17594     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17595
17596     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17597   }
17598
17599   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17600
17601   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17602           "Unsupported value type for operation");
17603
17604   // Use native supported vector instruction vplzcntd.
17605   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17606   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17607   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17608   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17609
17610   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17611 }
17612
17613 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17614                          SelectionDAG &DAG) {
17615   MVT VT = Op.getSimpleValueType();
17616   MVT OpVT = VT;
17617   unsigned NumBits = VT.getSizeInBits();
17618   SDLoc dl(Op);
17619
17620   if (VT.isVector() && Subtarget->hasAVX512())
17621     return LowerVectorCTLZ_AVX512(Op, DAG);
17622
17623   Op = Op.getOperand(0);
17624   if (VT == MVT::i8) {
17625     // Zero extend to i32 since there is not an i8 bsr.
17626     OpVT = MVT::i32;
17627     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17628   }
17629
17630   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17631   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17632   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17633
17634   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17635   SDValue Ops[] = {
17636     Op,
17637     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17638     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17639     Op.getValue(1)
17640   };
17641   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17642
17643   // Finally xor with NumBits-1.
17644   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17645                    DAG.getConstant(NumBits - 1, dl, OpVT));
17646
17647   if (VT == MVT::i8)
17648     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17649   return Op;
17650 }
17651
17652 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17653                                     SelectionDAG &DAG) {
17654   MVT VT = Op.getSimpleValueType();
17655   EVT OpVT = VT;
17656   unsigned NumBits = VT.getSizeInBits();
17657   SDLoc dl(Op);
17658
17659   if (VT.isVector() && Subtarget->hasAVX512())
17660     return LowerVectorCTLZ_AVX512(Op, DAG);
17661
17662   Op = Op.getOperand(0);
17663   if (VT == MVT::i8) {
17664     // Zero extend to i32 since there is not an i8 bsr.
17665     OpVT = MVT::i32;
17666     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17667   }
17668
17669   // Issue a bsr (scan bits in reverse).
17670   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17671   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17672
17673   // And xor with NumBits-1.
17674   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17675                    DAG.getConstant(NumBits - 1, dl, OpVT));
17676
17677   if (VT == MVT::i8)
17678     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17679   return Op;
17680 }
17681
17682 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17683   MVT VT = Op.getSimpleValueType();
17684   unsigned NumBits = VT.getScalarSizeInBits();
17685   SDLoc dl(Op);
17686
17687   if (VT.isVector()) {
17688     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17689
17690     SDValue N0 = Op.getOperand(0);
17691     SDValue Zero = DAG.getConstant(0, dl, VT);
17692
17693     // lsb(x) = (x & -x)
17694     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17695                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17696
17697     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17698     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17699         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17700       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17701       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17702                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17703     }
17704
17705     // cttz(x) = ctpop(lsb - 1)
17706     SDValue One = DAG.getConstant(1, dl, VT);
17707     return DAG.getNode(ISD::CTPOP, dl, VT,
17708                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17709   }
17710
17711   assert(Op.getOpcode() == ISD::CTTZ &&
17712          "Only scalar CTTZ requires custom lowering");
17713
17714   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17715   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17716   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17717
17718   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17719   SDValue Ops[] = {
17720     Op,
17721     DAG.getConstant(NumBits, dl, VT),
17722     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17723     Op.getValue(1)
17724   };
17725   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17726 }
17727
17728 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17729 // ones, and then concatenate the result back.
17730 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17731   MVT VT = Op.getSimpleValueType();
17732
17733   assert(VT.is256BitVector() && VT.isInteger() &&
17734          "Unsupported value type for operation");
17735
17736   unsigned NumElems = VT.getVectorNumElements();
17737   SDLoc dl(Op);
17738
17739   // Extract the LHS vectors
17740   SDValue LHS = Op.getOperand(0);
17741   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17742   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17743
17744   // Extract the RHS vectors
17745   SDValue RHS = Op.getOperand(1);
17746   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17747   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17748
17749   MVT EltVT = VT.getVectorElementType();
17750   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17751
17752   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17753                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17754                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17755 }
17756
17757 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17758   if (Op.getValueType() == MVT::i1)
17759     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17760                        Op.getOperand(0), Op.getOperand(1));
17761   assert(Op.getSimpleValueType().is256BitVector() &&
17762          Op.getSimpleValueType().isInteger() &&
17763          "Only handle AVX 256-bit vector integer operation");
17764   return Lower256IntArith(Op, DAG);
17765 }
17766
17767 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17768   if (Op.getValueType() == MVT::i1)
17769     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17770                        Op.getOperand(0), Op.getOperand(1));
17771   assert(Op.getSimpleValueType().is256BitVector() &&
17772          Op.getSimpleValueType().isInteger() &&
17773          "Only handle AVX 256-bit vector integer operation");
17774   return Lower256IntArith(Op, DAG);
17775 }
17776
17777 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17778   assert(Op.getSimpleValueType().is256BitVector() &&
17779          Op.getSimpleValueType().isInteger() &&
17780          "Only handle AVX 256-bit vector integer operation");
17781   return Lower256IntArith(Op, DAG);
17782 }
17783
17784 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17785                         SelectionDAG &DAG) {
17786   SDLoc dl(Op);
17787   MVT VT = Op.getSimpleValueType();
17788
17789   if (VT == MVT::i1)
17790     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17791
17792   // Decompose 256-bit ops into smaller 128-bit ops.
17793   if (VT.is256BitVector() && !Subtarget->hasInt256())
17794     return Lower256IntArith(Op, DAG);
17795
17796   SDValue A = Op.getOperand(0);
17797   SDValue B = Op.getOperand(1);
17798
17799   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17800   // pairs, multiply and truncate.
17801   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17802     if (Subtarget->hasInt256()) {
17803       if (VT == MVT::v32i8) {
17804         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17805         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17806         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17807         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17808         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17809         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17810         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17811         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17812                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17813                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17814       }
17815
17816       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17817       return DAG.getNode(
17818           ISD::TRUNCATE, dl, VT,
17819           DAG.getNode(ISD::MUL, dl, ExVT,
17820                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17821                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17822     }
17823
17824     assert(VT == MVT::v16i8 &&
17825            "Pre-AVX2 support only supports v16i8 multiplication");
17826     MVT ExVT = MVT::v8i16;
17827
17828     // Extract the lo parts and sign extend to i16
17829     SDValue ALo, BLo;
17830     if (Subtarget->hasSSE41()) {
17831       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17832       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17833     } else {
17834       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17835                               -1, 4, -1, 5, -1, 6, -1, 7};
17836       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17837       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17838       ALo = DAG.getBitcast(ExVT, ALo);
17839       BLo = DAG.getBitcast(ExVT, BLo);
17840       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17841       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17842     }
17843
17844     // Extract the hi parts and sign extend to i16
17845     SDValue AHi, BHi;
17846     if (Subtarget->hasSSE41()) {
17847       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17848                               -1, -1, -1, -1, -1, -1, -1, -1};
17849       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17850       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17851       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17852       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17853     } else {
17854       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17855                               -1, 12, -1, 13, -1, 14, -1, 15};
17856       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17857       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17858       AHi = DAG.getBitcast(ExVT, AHi);
17859       BHi = DAG.getBitcast(ExVT, BHi);
17860       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17861       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17862     }
17863
17864     // Multiply, mask the lower 8bits of the lo/hi results and pack
17865     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17866     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17867     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17868     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17869     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17870   }
17871
17872   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17873   if (VT == MVT::v4i32) {
17874     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17875            "Should not custom lower when pmuldq is available!");
17876
17877     // Extract the odd parts.
17878     static const int UnpackMask[] = { 1, -1, 3, -1 };
17879     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17880     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17881
17882     // Multiply the even parts.
17883     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17884     // Now multiply odd parts.
17885     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17886
17887     Evens = DAG.getBitcast(VT, Evens);
17888     Odds = DAG.getBitcast(VT, Odds);
17889
17890     // Merge the two vectors back together with a shuffle. This expands into 2
17891     // shuffles.
17892     static const int ShufMask[] = { 0, 4, 2, 6 };
17893     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17894   }
17895
17896   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17897          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17898
17899   //  Ahi = psrlqi(a, 32);
17900   //  Bhi = psrlqi(b, 32);
17901   //
17902   //  AloBlo = pmuludq(a, b);
17903   //  AloBhi = pmuludq(a, Bhi);
17904   //  AhiBlo = pmuludq(Ahi, b);
17905
17906   //  AloBhi = psllqi(AloBhi, 32);
17907   //  AhiBlo = psllqi(AhiBlo, 32);
17908   //  return AloBlo + AloBhi + AhiBlo;
17909
17910   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17911   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17912
17913   SDValue AhiBlo = Ahi;
17914   SDValue AloBhi = Bhi;
17915   // Bit cast to 32-bit vectors for MULUDQ
17916   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17917                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17918   A = DAG.getBitcast(MulVT, A);
17919   B = DAG.getBitcast(MulVT, B);
17920   Ahi = DAG.getBitcast(MulVT, Ahi);
17921   Bhi = DAG.getBitcast(MulVT, Bhi);
17922
17923   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17924   // After shifting right const values the result may be all-zero.
17925   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17926     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17927     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17928   }
17929   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17930     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17931     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17932   }
17933
17934   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17935   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17936 }
17937
17938 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17939   assert(Subtarget->isTargetWin64() && "Unexpected target");
17940   EVT VT = Op.getValueType();
17941   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17942          "Unexpected return type for lowering");
17943
17944   RTLIB::Libcall LC;
17945   bool isSigned;
17946   switch (Op->getOpcode()) {
17947   default: llvm_unreachable("Unexpected request for libcall!");
17948   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17949   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17950   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17951   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17952   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17953   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17954   }
17955
17956   SDLoc dl(Op);
17957   SDValue InChain = DAG.getEntryNode();
17958
17959   TargetLowering::ArgListTy Args;
17960   TargetLowering::ArgListEntry Entry;
17961   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17962     EVT ArgVT = Op->getOperand(i).getValueType();
17963     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17964            "Unexpected argument type for lowering");
17965     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17966     Entry.Node = StackPtr;
17967     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17968                            false, false, 16);
17969     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17970     Entry.Ty = PointerType::get(ArgTy,0);
17971     Entry.isSExt = false;
17972     Entry.isZExt = false;
17973     Args.push_back(Entry);
17974   }
17975
17976   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17977                                          getPointerTy(DAG.getDataLayout()));
17978
17979   TargetLowering::CallLoweringInfo CLI(DAG);
17980   CLI.setDebugLoc(dl).setChain(InChain)
17981     .setCallee(getLibcallCallingConv(LC),
17982                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17983                Callee, std::move(Args), 0)
17984     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17985
17986   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17987   return DAG.getBitcast(VT, CallInfo.first);
17988 }
17989
17990 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17991                              SelectionDAG &DAG) {
17992   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17993   MVT VT = Op0.getSimpleValueType();
17994   SDLoc dl(Op);
17995
17996   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17997          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17998
17999   // PMULxD operations multiply each even value (starting at 0) of LHS with
18000   // the related value of RHS and produce a widen result.
18001   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18002   // => <2 x i64> <ae|cg>
18003   //
18004   // In other word, to have all the results, we need to perform two PMULxD:
18005   // 1. one with the even values.
18006   // 2. one with the odd values.
18007   // To achieve #2, with need to place the odd values at an even position.
18008   //
18009   // Place the odd value at an even position (basically, shift all values 1
18010   // step to the left):
18011   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18012   // <a|b|c|d> => <b|undef|d|undef>
18013   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18014   // <e|f|g|h> => <f|undef|h|undef>
18015   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18016
18017   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18018   // ints.
18019   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18020   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18021   unsigned Opcode =
18022       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18023   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18024   // => <2 x i64> <ae|cg>
18025   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18026   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18027   // => <2 x i64> <bf|dh>
18028   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18029
18030   // Shuffle it back into the right order.
18031   SDValue Highs, Lows;
18032   if (VT == MVT::v8i32) {
18033     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18034     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18035     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18036     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18037   } else {
18038     const int HighMask[] = {1, 5, 3, 7};
18039     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18040     const int LowMask[] = {0, 4, 2, 6};
18041     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18042   }
18043
18044   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18045   // unsigned multiply.
18046   if (IsSigned && !Subtarget->hasSSE41()) {
18047     SDValue ShAmt = DAG.getConstant(
18048         31, dl,
18049         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18050     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18051                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18052     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18053                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18054
18055     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18056     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18057   }
18058
18059   // The first result of MUL_LOHI is actually the low value, followed by the
18060   // high value.
18061   SDValue Ops[] = {Lows, Highs};
18062   return DAG.getMergeValues(Ops, dl);
18063 }
18064
18065 // Return true if the required (according to Opcode) shift-imm form is natively
18066 // supported by the Subtarget
18067 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18068                                         unsigned Opcode) {
18069   if (VT.getScalarSizeInBits() < 16)
18070     return false;
18071
18072   if (VT.is512BitVector() &&
18073       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18074     return true;
18075
18076   bool LShift = VT.is128BitVector() ||
18077     (VT.is256BitVector() && Subtarget->hasInt256());
18078
18079   bool AShift = LShift && (Subtarget->hasVLX() ||
18080     (VT != MVT::v2i64 && VT != MVT::v4i64));
18081   return (Opcode == ISD::SRA) ? AShift : LShift;
18082 }
18083
18084 // The shift amount is a variable, but it is the same for all vector lanes.
18085 // These instructions are defined together with shift-immediate.
18086 static
18087 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18088                                       unsigned Opcode) {
18089   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18090 }
18091
18092 // Return true if the required (according to Opcode) variable-shift form is
18093 // natively supported by the Subtarget
18094 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18095                                     unsigned Opcode) {
18096
18097   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18098     return false;
18099
18100   // vXi16 supported only on AVX-512, BWI
18101   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18102     return false;
18103
18104   if (VT.is512BitVector() || Subtarget->hasVLX())
18105     return true;
18106
18107   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18108   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18109   return (Opcode == ISD::SRA) ? AShift : LShift;
18110 }
18111
18112 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18113                                          const X86Subtarget *Subtarget) {
18114   MVT VT = Op.getSimpleValueType();
18115   SDLoc dl(Op);
18116   SDValue R = Op.getOperand(0);
18117   SDValue Amt = Op.getOperand(1);
18118
18119   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18120     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18121
18122   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18123     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18124     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18125     SDValue Ex = DAG.getBitcast(ExVT, R);
18126
18127     if (ShiftAmt >= 32) {
18128       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18129       SDValue Upper =
18130           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18131       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18132                                                  ShiftAmt - 32, DAG);
18133       if (VT == MVT::v2i64)
18134         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18135       if (VT == MVT::v4i64)
18136         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18137                                   {9, 1, 11, 3, 13, 5, 15, 7});
18138     } else {
18139       // SRA upper i32, SHL whole i64 and select lower i32.
18140       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18141                                                  ShiftAmt, DAG);
18142       SDValue Lower =
18143           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18144       Lower = DAG.getBitcast(ExVT, Lower);
18145       if (VT == MVT::v2i64)
18146         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18147       if (VT == MVT::v4i64)
18148         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18149                                   {8, 1, 10, 3, 12, 5, 14, 7});
18150     }
18151     return DAG.getBitcast(VT, Ex);
18152   };
18153
18154   // Optimize shl/srl/sra with constant shift amount.
18155   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18156     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18157       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18158
18159       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18160         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18161
18162       // i64 SRA needs to be performed as partial shifts.
18163       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18164           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18165         return ArithmeticShiftRight64(ShiftAmt);
18166
18167       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18168         unsigned NumElts = VT.getVectorNumElements();
18169         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18170
18171         // Simple i8 add case
18172         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18173           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18174
18175         // ashr(R, 7)  === cmp_slt(R, 0)
18176         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18177           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18178           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18179         }
18180
18181         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18182         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18183           return SDValue();
18184
18185         if (Op.getOpcode() == ISD::SHL) {
18186           // Make a large shift.
18187           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18188                                                    R, ShiftAmt, DAG);
18189           SHL = DAG.getBitcast(VT, SHL);
18190           // Zero out the rightmost bits.
18191           SmallVector<SDValue, 32> V(
18192               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18193           return DAG.getNode(ISD::AND, dl, VT, SHL,
18194                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18195         }
18196         if (Op.getOpcode() == ISD::SRL) {
18197           // Make a large shift.
18198           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18199                                                    R, ShiftAmt, DAG);
18200           SRL = DAG.getBitcast(VT, SRL);
18201           // Zero out the leftmost bits.
18202           SmallVector<SDValue, 32> V(
18203               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18204           return DAG.getNode(ISD::AND, dl, VT, SRL,
18205                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18206         }
18207         if (Op.getOpcode() == ISD::SRA) {
18208           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18209           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18210           SmallVector<SDValue, 32> V(NumElts,
18211                                      DAG.getConstant(128 >> ShiftAmt, dl,
18212                                                      MVT::i8));
18213           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18214           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18215           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18216           return Res;
18217         }
18218         llvm_unreachable("Unknown shift opcode.");
18219       }
18220     }
18221   }
18222
18223   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18224   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18225       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18226
18227     // Peek through any splat that was introduced for i64 shift vectorization.
18228     int SplatIndex = -1;
18229     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18230       if (SVN->isSplat()) {
18231         SplatIndex = SVN->getSplatIndex();
18232         Amt = Amt.getOperand(0);
18233         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18234                "Splat shuffle referencing second operand");
18235       }
18236
18237     if (Amt.getOpcode() != ISD::BITCAST ||
18238         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18239       return SDValue();
18240
18241     Amt = Amt.getOperand(0);
18242     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18243                      VT.getVectorNumElements();
18244     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18245     uint64_t ShiftAmt = 0;
18246     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18247     for (unsigned i = 0; i != Ratio; ++i) {
18248       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18249       if (!C)
18250         return SDValue();
18251       // 6 == Log2(64)
18252       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18253     }
18254
18255     // Check remaining shift amounts (if not a splat).
18256     if (SplatIndex < 0) {
18257       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18258         uint64_t ShAmt = 0;
18259         for (unsigned j = 0; j != Ratio; ++j) {
18260           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18261           if (!C)
18262             return SDValue();
18263           // 6 == Log2(64)
18264           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18265         }
18266         if (ShAmt != ShiftAmt)
18267           return SDValue();
18268       }
18269     }
18270
18271     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18272       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18273
18274     if (Op.getOpcode() == ISD::SRA)
18275       return ArithmeticShiftRight64(ShiftAmt);
18276   }
18277
18278   return SDValue();
18279 }
18280
18281 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18282                                         const X86Subtarget* Subtarget) {
18283   MVT VT = Op.getSimpleValueType();
18284   SDLoc dl(Op);
18285   SDValue R = Op.getOperand(0);
18286   SDValue Amt = Op.getOperand(1);
18287
18288   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18289     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18290
18291   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18292     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18293
18294   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18295     SDValue BaseShAmt;
18296     MVT EltVT = VT.getVectorElementType();
18297
18298     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18299       // Check if this build_vector node is doing a splat.
18300       // If so, then set BaseShAmt equal to the splat value.
18301       BaseShAmt = BV->getSplatValue();
18302       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18303         BaseShAmt = SDValue();
18304     } else {
18305       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18306         Amt = Amt.getOperand(0);
18307
18308       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18309       if (SVN && SVN->isSplat()) {
18310         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18311         SDValue InVec = Amt.getOperand(0);
18312         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18313           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18314                  "Unexpected shuffle index found!");
18315           BaseShAmt = InVec.getOperand(SplatIdx);
18316         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18317            if (ConstantSDNode *C =
18318                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18319              if (C->getZExtValue() == SplatIdx)
18320                BaseShAmt = InVec.getOperand(1);
18321            }
18322         }
18323
18324         if (!BaseShAmt)
18325           // Avoid introducing an extract element from a shuffle.
18326           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18327                                   DAG.getIntPtrConstant(SplatIdx, dl));
18328       }
18329     }
18330
18331     if (BaseShAmt.getNode()) {
18332       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18333       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18334         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18335       else if (EltVT.bitsLT(MVT::i32))
18336         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18337
18338       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18339     }
18340   }
18341
18342   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18343   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18344       Amt.getOpcode() == ISD::BITCAST &&
18345       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18346     Amt = Amt.getOperand(0);
18347     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18348                      VT.getVectorNumElements();
18349     std::vector<SDValue> Vals(Ratio);
18350     for (unsigned i = 0; i != Ratio; ++i)
18351       Vals[i] = Amt.getOperand(i);
18352     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18353       for (unsigned j = 0; j != Ratio; ++j)
18354         if (Vals[j] != Amt.getOperand(i + j))
18355           return SDValue();
18356     }
18357
18358     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18359       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18360   }
18361   return SDValue();
18362 }
18363
18364 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18365                           SelectionDAG &DAG) {
18366   MVT VT = Op.getSimpleValueType();
18367   SDLoc dl(Op);
18368   SDValue R = Op.getOperand(0);
18369   SDValue Amt = Op.getOperand(1);
18370
18371   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18372   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18373
18374   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18375     return V;
18376
18377   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18378     return V;
18379
18380   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18381     return Op;
18382
18383   // XOP has 128-bit variable logical/arithmetic shifts.
18384   // +ve/-ve Amt = shift left/right.
18385   if (Subtarget->hasXOP() &&
18386       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18387        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18388     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18389       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18390       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18391     }
18392     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18393       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18394     if (Op.getOpcode() == ISD::SRA)
18395       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18396   }
18397
18398   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18399   // shifts per-lane and then shuffle the partial results back together.
18400   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18401     // Splat the shift amounts so the scalar shifts above will catch it.
18402     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18403     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18404     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18405     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18406     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18407   }
18408
18409   // i64 vector arithmetic shift can be emulated with the transform:
18410   // M = lshr(SIGN_BIT, Amt)
18411   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18412   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18413       Op.getOpcode() == ISD::SRA) {
18414     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18415     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18416     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18417     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18418     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18419     return R;
18420   }
18421
18422   // If possible, lower this packed shift into a vector multiply instead of
18423   // expanding it into a sequence of scalar shifts.
18424   // Do this only if the vector shift count is a constant build_vector.
18425   if (Op.getOpcode() == ISD::SHL &&
18426       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18427        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18428       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18429     SmallVector<SDValue, 8> Elts;
18430     MVT SVT = VT.getVectorElementType();
18431     unsigned SVTBits = SVT.getSizeInBits();
18432     APInt One(SVTBits, 1);
18433     unsigned NumElems = VT.getVectorNumElements();
18434
18435     for (unsigned i=0; i !=NumElems; ++i) {
18436       SDValue Op = Amt->getOperand(i);
18437       if (Op->getOpcode() == ISD::UNDEF) {
18438         Elts.push_back(Op);
18439         continue;
18440       }
18441
18442       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18443       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18444       uint64_t ShAmt = C.getZExtValue();
18445       if (ShAmt >= SVTBits) {
18446         Elts.push_back(DAG.getUNDEF(SVT));
18447         continue;
18448       }
18449       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18450     }
18451     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18452     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18453   }
18454
18455   // Lower SHL with variable shift amount.
18456   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18457     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18458
18459     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18460                      DAG.getConstant(0x3f800000U, dl, VT));
18461     Op = DAG.getBitcast(MVT::v4f32, Op);
18462     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18463     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18464   }
18465
18466   // If possible, lower this shift as a sequence of two shifts by
18467   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18468   // Example:
18469   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18470   //
18471   // Could be rewritten as:
18472   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18473   //
18474   // The advantage is that the two shifts from the example would be
18475   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18476   // the vector shift into four scalar shifts plus four pairs of vector
18477   // insert/extract.
18478   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18479       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18480     unsigned TargetOpcode = X86ISD::MOVSS;
18481     bool CanBeSimplified;
18482     // The splat value for the first packed shift (the 'X' from the example).
18483     SDValue Amt1 = Amt->getOperand(0);
18484     // The splat value for the second packed shift (the 'Y' from the example).
18485     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18486                                         Amt->getOperand(2);
18487
18488     // See if it is possible to replace this node with a sequence of
18489     // two shifts followed by a MOVSS/MOVSD
18490     if (VT == MVT::v4i32) {
18491       // Check if it is legal to use a MOVSS.
18492       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18493                         Amt2 == Amt->getOperand(3);
18494       if (!CanBeSimplified) {
18495         // Otherwise, check if we can still simplify this node using a MOVSD.
18496         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18497                           Amt->getOperand(2) == Amt->getOperand(3);
18498         TargetOpcode = X86ISD::MOVSD;
18499         Amt2 = Amt->getOperand(2);
18500       }
18501     } else {
18502       // Do similar checks for the case where the machine value type
18503       // is MVT::v8i16.
18504       CanBeSimplified = Amt1 == Amt->getOperand(1);
18505       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18506         CanBeSimplified = Amt2 == Amt->getOperand(i);
18507
18508       if (!CanBeSimplified) {
18509         TargetOpcode = X86ISD::MOVSD;
18510         CanBeSimplified = true;
18511         Amt2 = Amt->getOperand(4);
18512         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18513           CanBeSimplified = Amt1 == Amt->getOperand(i);
18514         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18515           CanBeSimplified = Amt2 == Amt->getOperand(j);
18516       }
18517     }
18518
18519     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18520         isa<ConstantSDNode>(Amt2)) {
18521       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18522       MVT CastVT = MVT::v4i32;
18523       SDValue Splat1 =
18524         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18525       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18526       SDValue Splat2 =
18527         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18528       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18529       if (TargetOpcode == X86ISD::MOVSD)
18530         CastVT = MVT::v2i64;
18531       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18532       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18533       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18534                                             BitCast1, DAG);
18535       return DAG.getBitcast(VT, Result);
18536     }
18537   }
18538
18539   // v4i32 Non Uniform Shifts.
18540   // If the shift amount is constant we can shift each lane using the SSE2
18541   // immediate shifts, else we need to zero-extend each lane to the lower i64
18542   // and shift using the SSE2 variable shifts.
18543   // The separate results can then be blended together.
18544   if (VT == MVT::v4i32) {
18545     unsigned Opc = Op.getOpcode();
18546     SDValue Amt0, Amt1, Amt2, Amt3;
18547     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18548       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18549       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18550       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18551       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18552     } else {
18553       // ISD::SHL is handled above but we include it here for completeness.
18554       switch (Opc) {
18555       default:
18556         llvm_unreachable("Unknown target vector shift node");
18557       case ISD::SHL:
18558         Opc = X86ISD::VSHL;
18559         break;
18560       case ISD::SRL:
18561         Opc = X86ISD::VSRL;
18562         break;
18563       case ISD::SRA:
18564         Opc = X86ISD::VSRA;
18565         break;
18566       }
18567       // The SSE2 shifts use the lower i64 as the same shift amount for
18568       // all lanes and the upper i64 is ignored. These shuffle masks
18569       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18570       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18571       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18572       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18573       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18574       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18575     }
18576
18577     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18578     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18579     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18580     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18581     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18582     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18583     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18584   }
18585
18586   if (VT == MVT::v16i8 ||
18587       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18588     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18589     unsigned ShiftOpcode = Op->getOpcode();
18590
18591     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18592       // On SSE41 targets we make use of the fact that VSELECT lowers
18593       // to PBLENDVB which selects bytes based just on the sign bit.
18594       if (Subtarget->hasSSE41()) {
18595         V0 = DAG.getBitcast(VT, V0);
18596         V1 = DAG.getBitcast(VT, V1);
18597         Sel = DAG.getBitcast(VT, Sel);
18598         return DAG.getBitcast(SelVT,
18599                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18600       }
18601       // On pre-SSE41 targets we test for the sign bit by comparing to
18602       // zero - a negative value will set all bits of the lanes to true
18603       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18604       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18605       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18606       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18607     };
18608
18609     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18610     // We can safely do this using i16 shifts as we're only interested in
18611     // the 3 lower bits of each byte.
18612     Amt = DAG.getBitcast(ExtVT, Amt);
18613     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18614     Amt = DAG.getBitcast(VT, Amt);
18615
18616     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18617       // r = VSELECT(r, shift(r, 4), a);
18618       SDValue M =
18619           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18620       R = SignBitSelect(VT, Amt, M, R);
18621
18622       // a += a
18623       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18624
18625       // r = VSELECT(r, shift(r, 2), a);
18626       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18627       R = SignBitSelect(VT, Amt, M, R);
18628
18629       // a += a
18630       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18631
18632       // return VSELECT(r, shift(r, 1), a);
18633       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18634       R = SignBitSelect(VT, Amt, M, R);
18635       return R;
18636     }
18637
18638     if (Op->getOpcode() == ISD::SRA) {
18639       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18640       // so we can correctly sign extend. We don't care what happens to the
18641       // lower byte.
18642       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18643       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18644       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18645       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18646       ALo = DAG.getBitcast(ExtVT, ALo);
18647       AHi = DAG.getBitcast(ExtVT, AHi);
18648       RLo = DAG.getBitcast(ExtVT, RLo);
18649       RHi = DAG.getBitcast(ExtVT, RHi);
18650
18651       // r = VSELECT(r, shift(r, 4), a);
18652       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18653                                 DAG.getConstant(4, dl, ExtVT));
18654       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18655                                 DAG.getConstant(4, dl, ExtVT));
18656       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18657       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18658
18659       // a += a
18660       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18661       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18662
18663       // r = VSELECT(r, shift(r, 2), a);
18664       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18665                         DAG.getConstant(2, dl, ExtVT));
18666       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18667                         DAG.getConstant(2, dl, ExtVT));
18668       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18669       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18670
18671       // a += a
18672       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18673       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18674
18675       // r = VSELECT(r, shift(r, 1), a);
18676       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18677                         DAG.getConstant(1, dl, ExtVT));
18678       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18679                         DAG.getConstant(1, dl, ExtVT));
18680       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18681       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18682
18683       // Logical shift the result back to the lower byte, leaving a zero upper
18684       // byte
18685       // meaning that we can safely pack with PACKUSWB.
18686       RLo =
18687           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18688       RHi =
18689           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18690       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18691     }
18692   }
18693
18694   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18695   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18696   // solution better.
18697   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18698     MVT ExtVT = MVT::v8i32;
18699     unsigned ExtOpc =
18700         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18701     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18702     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18703     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18704                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18705   }
18706
18707   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18708     MVT ExtVT = MVT::v8i32;
18709     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18710     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18711     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18712     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18713     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18714     ALo = DAG.getBitcast(ExtVT, ALo);
18715     AHi = DAG.getBitcast(ExtVT, AHi);
18716     RLo = DAG.getBitcast(ExtVT, RLo);
18717     RHi = DAG.getBitcast(ExtVT, RHi);
18718     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18719     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18720     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18721     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18722     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18723   }
18724
18725   if (VT == MVT::v8i16) {
18726     unsigned ShiftOpcode = Op->getOpcode();
18727
18728     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18729       // On SSE41 targets we make use of the fact that VSELECT lowers
18730       // to PBLENDVB which selects bytes based just on the sign bit.
18731       if (Subtarget->hasSSE41()) {
18732         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18733         V0 = DAG.getBitcast(ExtVT, V0);
18734         V1 = DAG.getBitcast(ExtVT, V1);
18735         Sel = DAG.getBitcast(ExtVT, Sel);
18736         return DAG.getBitcast(
18737             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18738       }
18739       // On pre-SSE41 targets we splat the sign bit - a negative value will
18740       // set all bits of the lanes to true and VSELECT uses that in
18741       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18742       SDValue C =
18743           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18744       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18745     };
18746
18747     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18748     if (Subtarget->hasSSE41()) {
18749       // On SSE41 targets we need to replicate the shift mask in both
18750       // bytes for PBLENDVB.
18751       Amt = DAG.getNode(
18752           ISD::OR, dl, VT,
18753           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18754           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18755     } else {
18756       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18757     }
18758
18759     // r = VSELECT(r, shift(r, 8), a);
18760     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18761     R = SignBitSelect(Amt, M, R);
18762
18763     // a += a
18764     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18765
18766     // r = VSELECT(r, shift(r, 4), a);
18767     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18768     R = SignBitSelect(Amt, M, R);
18769
18770     // a += a
18771     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18772
18773     // r = VSELECT(r, shift(r, 2), a);
18774     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18775     R = SignBitSelect(Amt, M, R);
18776
18777     // a += a
18778     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18779
18780     // return VSELECT(r, shift(r, 1), a);
18781     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18782     R = SignBitSelect(Amt, M, R);
18783     return R;
18784   }
18785
18786   // Decompose 256-bit shifts into smaller 128-bit shifts.
18787   if (VT.is256BitVector()) {
18788     unsigned NumElems = VT.getVectorNumElements();
18789     MVT EltVT = VT.getVectorElementType();
18790     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18791
18792     // Extract the two vectors
18793     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18794     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18795
18796     // Recreate the shift amount vectors
18797     SDValue Amt1, Amt2;
18798     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18799       // Constant shift amount
18800       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18801       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18802       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18803
18804       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18805       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18806     } else {
18807       // Variable shift amount
18808       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18809       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18810     }
18811
18812     // Issue new vector shifts for the smaller types
18813     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18814     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18815
18816     // Concatenate the result back
18817     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18818   }
18819
18820   return SDValue();
18821 }
18822
18823 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18824                            SelectionDAG &DAG) {
18825   MVT VT = Op.getSimpleValueType();
18826   SDLoc DL(Op);
18827   SDValue R = Op.getOperand(0);
18828   SDValue Amt = Op.getOperand(1);
18829
18830   assert(VT.isVector() && "Custom lowering only for vector rotates!");
18831   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18832   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18833
18834   // XOP has 128-bit vector variable + immediate rotates.
18835   // +ve/-ve Amt = rotate left/right.
18836
18837   // Split 256-bit integers.
18838   if (VT.is256BitVector())
18839     return Lower256IntArith(Op, DAG);
18840
18841   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
18842
18843   // Attempt to rotate by immediate.
18844   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18845     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18846       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18847       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18848       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18849                          DAG.getConstant(RotateAmt, DL, MVT::i8));
18850     }
18851   }
18852
18853   // Use general rotate by variable (per-element).
18854   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18855 }
18856
18857 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18858   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18859   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18860   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18861   // has only one use.
18862   SDNode *N = Op.getNode();
18863   SDValue LHS = N->getOperand(0);
18864   SDValue RHS = N->getOperand(1);
18865   unsigned BaseOp = 0;
18866   unsigned Cond = 0;
18867   SDLoc DL(Op);
18868   switch (Op.getOpcode()) {
18869   default: llvm_unreachable("Unknown ovf instruction!");
18870   case ISD::SADDO:
18871     // A subtract of one will be selected as a INC. Note that INC doesn't
18872     // set CF, so we can't do this for UADDO.
18873     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18874       if (C->isOne()) {
18875         BaseOp = X86ISD::INC;
18876         Cond = X86::COND_O;
18877         break;
18878       }
18879     BaseOp = X86ISD::ADD;
18880     Cond = X86::COND_O;
18881     break;
18882   case ISD::UADDO:
18883     BaseOp = X86ISD::ADD;
18884     Cond = X86::COND_B;
18885     break;
18886   case ISD::SSUBO:
18887     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18888     // set CF, so we can't do this for USUBO.
18889     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18890       if (C->isOne()) {
18891         BaseOp = X86ISD::DEC;
18892         Cond = X86::COND_O;
18893         break;
18894       }
18895     BaseOp = X86ISD::SUB;
18896     Cond = X86::COND_O;
18897     break;
18898   case ISD::USUBO:
18899     BaseOp = X86ISD::SUB;
18900     Cond = X86::COND_B;
18901     break;
18902   case ISD::SMULO:
18903     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18904     Cond = X86::COND_O;
18905     break;
18906   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18907     if (N->getValueType(0) == MVT::i8) {
18908       BaseOp = X86ISD::UMUL8;
18909       Cond = X86::COND_O;
18910       break;
18911     }
18912     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18913                                  MVT::i32);
18914     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18915
18916     SDValue SetCC =
18917       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18918                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18919                   SDValue(Sum.getNode(), 2));
18920
18921     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18922   }
18923   }
18924
18925   // Also sets EFLAGS.
18926   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18927   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18928
18929   SDValue SetCC =
18930     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18931                 DAG.getConstant(Cond, DL, MVT::i32),
18932                 SDValue(Sum.getNode(), 1));
18933
18934   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18935 }
18936
18937 /// Returns true if the operand type is exactly twice the native width, and
18938 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18939 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18940 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18941 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18942   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18943
18944   if (OpWidth == 64)
18945     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18946   else if (OpWidth == 128)
18947     return Subtarget->hasCmpxchg16b();
18948   else
18949     return false;
18950 }
18951
18952 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18953   return needsCmpXchgNb(SI->getValueOperand()->getType());
18954 }
18955
18956 // Note: this turns large loads into lock cmpxchg8b/16b.
18957 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18958 TargetLowering::AtomicExpansionKind
18959 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18960   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18961   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18962                                                : AtomicExpansionKind::None;
18963 }
18964
18965 TargetLowering::AtomicExpansionKind
18966 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18967   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18968   Type *MemType = AI->getType();
18969
18970   // If the operand is too big, we must see if cmpxchg8/16b is available
18971   // and default to library calls otherwise.
18972   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18973     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18974                                    : AtomicExpansionKind::None;
18975   }
18976
18977   AtomicRMWInst::BinOp Op = AI->getOperation();
18978   switch (Op) {
18979   default:
18980     llvm_unreachable("Unknown atomic operation");
18981   case AtomicRMWInst::Xchg:
18982   case AtomicRMWInst::Add:
18983   case AtomicRMWInst::Sub:
18984     // It's better to use xadd, xsub or xchg for these in all cases.
18985     return AtomicExpansionKind::None;
18986   case AtomicRMWInst::Or:
18987   case AtomicRMWInst::And:
18988   case AtomicRMWInst::Xor:
18989     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18990     // prefix to a normal instruction for these operations.
18991     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18992                             : AtomicExpansionKind::None;
18993   case AtomicRMWInst::Nand:
18994   case AtomicRMWInst::Max:
18995   case AtomicRMWInst::Min:
18996   case AtomicRMWInst::UMax:
18997   case AtomicRMWInst::UMin:
18998     // These always require a non-trivial set of data operations on x86. We must
18999     // use a cmpxchg loop.
19000     return AtomicExpansionKind::CmpXChg;
19001   }
19002 }
19003
19004 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19005   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19006   // no-sse2). There isn't any reason to disable it if the target processor
19007   // supports it.
19008   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19009 }
19010
19011 LoadInst *
19012 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19013   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19014   Type *MemType = AI->getType();
19015   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19016   // there is no benefit in turning such RMWs into loads, and it is actually
19017   // harmful as it introduces a mfence.
19018   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19019     return nullptr;
19020
19021   auto Builder = IRBuilder<>(AI);
19022   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19023   auto SynchScope = AI->getSynchScope();
19024   // We must restrict the ordering to avoid generating loads with Release or
19025   // ReleaseAcquire orderings.
19026   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19027   auto Ptr = AI->getPointerOperand();
19028
19029   // Before the load we need a fence. Here is an example lifted from
19030   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19031   // is required:
19032   // Thread 0:
19033   //   x.store(1, relaxed);
19034   //   r1 = y.fetch_add(0, release);
19035   // Thread 1:
19036   //   y.fetch_add(42, acquire);
19037   //   r2 = x.load(relaxed);
19038   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19039   // lowered to just a load without a fence. A mfence flushes the store buffer,
19040   // making the optimization clearly correct.
19041   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19042   // otherwise, we might be able to be more aggressive on relaxed idempotent
19043   // rmw. In practice, they do not look useful, so we don't try to be
19044   // especially clever.
19045   if (SynchScope == SingleThread)
19046     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19047     // the IR level, so we must wrap it in an intrinsic.
19048     return nullptr;
19049
19050   if (!hasMFENCE(*Subtarget))
19051     // FIXME: it might make sense to use a locked operation here but on a
19052     // different cache-line to prevent cache-line bouncing. In practice it
19053     // is probably a small win, and x86 processors without mfence are rare
19054     // enough that we do not bother.
19055     return nullptr;
19056
19057   Function *MFence =
19058       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19059   Builder.CreateCall(MFence, {});
19060
19061   // Finally we can emit the atomic load.
19062   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19063           AI->getType()->getPrimitiveSizeInBits());
19064   Loaded->setAtomic(Order, SynchScope);
19065   AI->replaceAllUsesWith(Loaded);
19066   AI->eraseFromParent();
19067   return Loaded;
19068 }
19069
19070 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19071                                  SelectionDAG &DAG) {
19072   SDLoc dl(Op);
19073   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19074     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19075   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19076     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19077
19078   // The only fence that needs an instruction is a sequentially-consistent
19079   // cross-thread fence.
19080   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19081     if (hasMFENCE(*Subtarget))
19082       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19083
19084     SDValue Chain = Op.getOperand(0);
19085     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19086     SDValue Ops[] = {
19087       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19088       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19089       DAG.getRegister(0, MVT::i32),            // Index
19090       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19091       DAG.getRegister(0, MVT::i32),            // Segment.
19092       Zero,
19093       Chain
19094     };
19095     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19096     return SDValue(Res, 0);
19097   }
19098
19099   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19100   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19101 }
19102
19103 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19104                              SelectionDAG &DAG) {
19105   MVT T = Op.getSimpleValueType();
19106   SDLoc DL(Op);
19107   unsigned Reg = 0;
19108   unsigned size = 0;
19109   switch(T.SimpleTy) {
19110   default: llvm_unreachable("Invalid value type!");
19111   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19112   case MVT::i16: Reg = X86::AX;  size = 2; break;
19113   case MVT::i32: Reg = X86::EAX; size = 4; break;
19114   case MVT::i64:
19115     assert(Subtarget->is64Bit() && "Node not type legal!");
19116     Reg = X86::RAX; size = 8;
19117     break;
19118   }
19119   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19120                                   Op.getOperand(2), SDValue());
19121   SDValue Ops[] = { cpIn.getValue(0),
19122                     Op.getOperand(1),
19123                     Op.getOperand(3),
19124                     DAG.getTargetConstant(size, DL, MVT::i8),
19125                     cpIn.getValue(1) };
19126   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19127   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19128   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19129                                            Ops, T, MMO);
19130
19131   SDValue cpOut =
19132     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19133   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19134                                       MVT::i32, cpOut.getValue(2));
19135   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19136                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19137                                 EFLAGS);
19138
19139   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19140   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19141   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19142   return SDValue();
19143 }
19144
19145 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19146                             SelectionDAG &DAG) {
19147   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19148   MVT DstVT = Op.getSimpleValueType();
19149
19150   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19151     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19152     if (DstVT != MVT::f64)
19153       // This conversion needs to be expanded.
19154       return SDValue();
19155
19156     SDValue InVec = Op->getOperand(0);
19157     SDLoc dl(Op);
19158     unsigned NumElts = SrcVT.getVectorNumElements();
19159     MVT SVT = SrcVT.getVectorElementType();
19160
19161     // Widen the vector in input in the case of MVT::v2i32.
19162     // Example: from MVT::v2i32 to MVT::v4i32.
19163     SmallVector<SDValue, 16> Elts;
19164     for (unsigned i = 0, e = NumElts; i != e; ++i)
19165       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19166                                  DAG.getIntPtrConstant(i, dl)));
19167
19168     // Explicitly mark the extra elements as Undef.
19169     Elts.append(NumElts, DAG.getUNDEF(SVT));
19170
19171     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19172     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19173     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19174     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19175                        DAG.getIntPtrConstant(0, dl));
19176   }
19177
19178   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19179          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19180   assert((DstVT == MVT::i64 ||
19181           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19182          "Unexpected custom BITCAST");
19183   // i64 <=> MMX conversions are Legal.
19184   if (SrcVT==MVT::i64 && DstVT.isVector())
19185     return Op;
19186   if (DstVT==MVT::i64 && SrcVT.isVector())
19187     return Op;
19188   // MMX <=> MMX conversions are Legal.
19189   if (SrcVT.isVector() && DstVT.isVector())
19190     return Op;
19191   // All other conversions need to be expanded.
19192   return SDValue();
19193 }
19194
19195 /// Compute the horizontal sum of bytes in V for the elements of VT.
19196 ///
19197 /// Requires V to be a byte vector and VT to be an integer vector type with
19198 /// wider elements than V's type. The width of the elements of VT determines
19199 /// how many bytes of V are summed horizontally to produce each element of the
19200 /// result.
19201 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19202                                       const X86Subtarget *Subtarget,
19203                                       SelectionDAG &DAG) {
19204   SDLoc DL(V);
19205   MVT ByteVecVT = V.getSimpleValueType();
19206   MVT EltVT = VT.getVectorElementType();
19207   int NumElts = VT.getVectorNumElements();
19208   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19209          "Expected value to have byte element type.");
19210   assert(EltVT != MVT::i8 &&
19211          "Horizontal byte sum only makes sense for wider elements!");
19212   unsigned VecSize = VT.getSizeInBits();
19213   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19214
19215   // PSADBW instruction horizontally add all bytes and leave the result in i64
19216   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19217   if (EltVT == MVT::i64) {
19218     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19219     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19220     return DAG.getBitcast(VT, V);
19221   }
19222
19223   if (EltVT == MVT::i32) {
19224     // We unpack the low half and high half into i32s interleaved with zeros so
19225     // that we can use PSADBW to horizontally sum them. The most useful part of
19226     // this is that it lines up the results of two PSADBW instructions to be
19227     // two v2i64 vectors which concatenated are the 4 population counts. We can
19228     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19229     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19230     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19231     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19232
19233     // Do the horizontal sums into two v2i64s.
19234     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19235     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19236                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19237     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19238                        DAG.getBitcast(ByteVecVT, High), Zeros);
19239
19240     // Merge them together.
19241     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19242     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19243                     DAG.getBitcast(ShortVecVT, Low),
19244                     DAG.getBitcast(ShortVecVT, High));
19245
19246     return DAG.getBitcast(VT, V);
19247   }
19248
19249   // The only element type left is i16.
19250   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19251
19252   // To obtain pop count for each i16 element starting from the pop count for
19253   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19254   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19255   // directly supported.
19256   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19257   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19258   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19259   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19260                   DAG.getBitcast(ByteVecVT, V));
19261   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19262 }
19263
19264 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19265                                         const X86Subtarget *Subtarget,
19266                                         SelectionDAG &DAG) {
19267   MVT VT = Op.getSimpleValueType();
19268   MVT EltVT = VT.getVectorElementType();
19269   unsigned VecSize = VT.getSizeInBits();
19270
19271   // Implement a lookup table in register by using an algorithm based on:
19272   // http://wm.ite.pl/articles/sse-popcount.html
19273   //
19274   // The general idea is that every lower byte nibble in the input vector is an
19275   // index into a in-register pre-computed pop count table. We then split up the
19276   // input vector in two new ones: (1) a vector with only the shifted-right
19277   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19278   // masked out higher ones) for each byte. PSHUB is used separately with both
19279   // to index the in-register table. Next, both are added and the result is a
19280   // i8 vector where each element contains the pop count for input byte.
19281   //
19282   // To obtain the pop count for elements != i8, we follow up with the same
19283   // approach and use additional tricks as described below.
19284   //
19285   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19286                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19287                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19288                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19289
19290   int NumByteElts = VecSize / 8;
19291   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19292   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19293   SmallVector<SDValue, 16> LUTVec;
19294   for (int i = 0; i < NumByteElts; ++i)
19295     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19296   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19297   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19298                                   DAG.getConstant(0x0F, DL, MVT::i8));
19299   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19300
19301   // High nibbles
19302   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19303   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19304   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19305
19306   // Low nibbles
19307   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19308
19309   // The input vector is used as the shuffle mask that index elements into the
19310   // LUT. After counting low and high nibbles, add the vector to obtain the
19311   // final pop count per i8 element.
19312   SDValue HighPopCnt =
19313       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19314   SDValue LowPopCnt =
19315       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19316   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19317
19318   if (EltVT == MVT::i8)
19319     return PopCnt;
19320
19321   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19322 }
19323
19324 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19325                                        const X86Subtarget *Subtarget,
19326                                        SelectionDAG &DAG) {
19327   MVT VT = Op.getSimpleValueType();
19328   assert(VT.is128BitVector() &&
19329          "Only 128-bit vector bitmath lowering supported.");
19330
19331   int VecSize = VT.getSizeInBits();
19332   MVT EltVT = VT.getVectorElementType();
19333   int Len = EltVT.getSizeInBits();
19334
19335   // This is the vectorized version of the "best" algorithm from
19336   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19337   // with a minor tweak to use a series of adds + shifts instead of vector
19338   // multiplications. Implemented for all integer vector types. We only use
19339   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19340   // much faster, even faster than using native popcnt instructions.
19341
19342   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19343     MVT VT = V.getSimpleValueType();
19344     SmallVector<SDValue, 32> Shifters(
19345         VT.getVectorNumElements(),
19346         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19347     return DAG.getNode(OpCode, DL, VT, V,
19348                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19349   };
19350   auto GetMask = [&](SDValue V, APInt Mask) {
19351     MVT VT = V.getSimpleValueType();
19352     SmallVector<SDValue, 32> Masks(
19353         VT.getVectorNumElements(),
19354         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19355     return DAG.getNode(ISD::AND, DL, VT, V,
19356                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19357   };
19358
19359   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19360   // x86, so set the SRL type to have elements at least i16 wide. This is
19361   // correct because all of our SRLs are followed immediately by a mask anyways
19362   // that handles any bits that sneak into the high bits of the byte elements.
19363   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19364
19365   SDValue V = Op;
19366
19367   // v = v - ((v >> 1) & 0x55555555...)
19368   SDValue Srl =
19369       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19370   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19371   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19372
19373   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19374   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19375   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19376   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19377   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19378
19379   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19380   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19381   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19382   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19383
19384   // At this point, V contains the byte-wise population count, and we are
19385   // merely doing a horizontal sum if necessary to get the wider element
19386   // counts.
19387   if (EltVT == MVT::i8)
19388     return V;
19389
19390   return LowerHorizontalByteSum(
19391       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19392       DAG);
19393 }
19394
19395 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19396                                 SelectionDAG &DAG) {
19397   MVT VT = Op.getSimpleValueType();
19398   // FIXME: Need to add AVX-512 support here!
19399   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19400          "Unknown CTPOP type to handle");
19401   SDLoc DL(Op.getNode());
19402   SDValue Op0 = Op.getOperand(0);
19403
19404   if (!Subtarget->hasSSSE3()) {
19405     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19406     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19407     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19408   }
19409
19410   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19411     unsigned NumElems = VT.getVectorNumElements();
19412
19413     // Extract each 128-bit vector, compute pop count and concat the result.
19414     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19415     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19416
19417     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19418                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19419                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19420   }
19421
19422   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19423 }
19424
19425 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19426                           SelectionDAG &DAG) {
19427   assert(Op.getSimpleValueType().isVector() &&
19428          "We only do custom lowering for vector population count.");
19429   return LowerVectorCTPOP(Op, Subtarget, DAG);
19430 }
19431
19432 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19433   SDNode *Node = Op.getNode();
19434   SDLoc dl(Node);
19435   EVT T = Node->getValueType(0);
19436   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19437                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19438   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19439                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19440                        Node->getOperand(0),
19441                        Node->getOperand(1), negOp,
19442                        cast<AtomicSDNode>(Node)->getMemOperand(),
19443                        cast<AtomicSDNode>(Node)->getOrdering(),
19444                        cast<AtomicSDNode>(Node)->getSynchScope());
19445 }
19446
19447 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19448   SDNode *Node = Op.getNode();
19449   SDLoc dl(Node);
19450   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19451
19452   // Convert seq_cst store -> xchg
19453   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19454   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19455   //        (The only way to get a 16-byte store is cmpxchg16b)
19456   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19457   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19458       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19459     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19460                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19461                                  Node->getOperand(0),
19462                                  Node->getOperand(1), Node->getOperand(2),
19463                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19464                                  cast<AtomicSDNode>(Node)->getOrdering(),
19465                                  cast<AtomicSDNode>(Node)->getSynchScope());
19466     return Swap.getValue(1);
19467   }
19468   // Other atomic stores have a simple pattern.
19469   return Op;
19470 }
19471
19472 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19473   MVT VT = Op.getNode()->getSimpleValueType(0);
19474
19475   // Let legalize expand this if it isn't a legal type yet.
19476   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19477     return SDValue();
19478
19479   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19480
19481   unsigned Opc;
19482   bool ExtraOp = false;
19483   switch (Op.getOpcode()) {
19484   default: llvm_unreachable("Invalid code");
19485   case ISD::ADDC: Opc = X86ISD::ADD; break;
19486   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19487   case ISD::SUBC: Opc = X86ISD::SUB; break;
19488   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19489   }
19490
19491   if (!ExtraOp)
19492     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19493                        Op.getOperand(1));
19494   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19495                      Op.getOperand(1), Op.getOperand(2));
19496 }
19497
19498 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19499                             SelectionDAG &DAG) {
19500   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19501
19502   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19503   // which returns the values as { float, float } (in XMM0) or
19504   // { double, double } (which is returned in XMM0, XMM1).
19505   SDLoc dl(Op);
19506   SDValue Arg = Op.getOperand(0);
19507   EVT ArgVT = Arg.getValueType();
19508   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19509
19510   TargetLowering::ArgListTy Args;
19511   TargetLowering::ArgListEntry Entry;
19512
19513   Entry.Node = Arg;
19514   Entry.Ty = ArgTy;
19515   Entry.isSExt = false;
19516   Entry.isZExt = false;
19517   Args.push_back(Entry);
19518
19519   bool isF64 = ArgVT == MVT::f64;
19520   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19521   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19522   // the results are returned via SRet in memory.
19523   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19525   SDValue Callee =
19526       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19527
19528   Type *RetTy = isF64
19529     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19530     : (Type*)VectorType::get(ArgTy, 4);
19531
19532   TargetLowering::CallLoweringInfo CLI(DAG);
19533   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19534     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19535
19536   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19537
19538   if (isF64)
19539     // Returned in xmm0 and xmm1.
19540     return CallResult.first;
19541
19542   // Returned in bits 0:31 and 32:64 xmm0.
19543   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19544                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19545   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19546                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19547   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19548   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19549 }
19550
19551 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19552                              SelectionDAG &DAG) {
19553   assert(Subtarget->hasAVX512() &&
19554          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19555
19556   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19557   MVT VT = N->getValue().getSimpleValueType();
19558   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19559   SDLoc dl(Op);
19560
19561   // X86 scatter kills mask register, so its type should be added to
19562   // the list of return values
19563   if (N->getNumValues() == 1) {
19564     SDValue Index = N->getIndex();
19565     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19566         !Index.getSimpleValueType().is512BitVector())
19567       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19568
19569     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19570     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19571                       N->getOperand(3), Index };
19572
19573     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19574     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19575     return SDValue(NewScatter.getNode(), 0);
19576   }
19577   return Op;
19578 }
19579
19580 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19581                             SelectionDAG &DAG) {
19582   assert(Subtarget->hasAVX512() &&
19583          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19584
19585   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19586   MVT VT = Op.getSimpleValueType();
19587   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19588   SDLoc dl(Op);
19589
19590   SDValue Index = N->getIndex();
19591   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19592       !Index.getSimpleValueType().is512BitVector()) {
19593     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19594     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19595                       N->getOperand(3), Index };
19596     DAG.UpdateNodeOperands(N, Ops);
19597   }
19598   return Op;
19599 }
19600
19601 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19602                                                     SelectionDAG &DAG) const {
19603   // TODO: Eventually, the lowering of these nodes should be informed by or
19604   // deferred to the GC strategy for the function in which they appear. For
19605   // now, however, they must be lowered to something. Since they are logically
19606   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19607   // require special handling for these nodes), lower them as literal NOOPs for
19608   // the time being.
19609   SmallVector<SDValue, 2> Ops;
19610
19611   Ops.push_back(Op.getOperand(0));
19612   if (Op->getGluedNode())
19613     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19614
19615   SDLoc OpDL(Op);
19616   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19617   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19618
19619   return NOOP;
19620 }
19621
19622 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19623                                                   SelectionDAG &DAG) const {
19624   // TODO: Eventually, the lowering of these nodes should be informed by or
19625   // deferred to the GC strategy for the function in which they appear. For
19626   // now, however, they must be lowered to something. Since they are logically
19627   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19628   // require special handling for these nodes), lower them as literal NOOPs for
19629   // the time being.
19630   SmallVector<SDValue, 2> Ops;
19631
19632   Ops.push_back(Op.getOperand(0));
19633   if (Op->getGluedNode())
19634     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19635
19636   SDLoc OpDL(Op);
19637   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19638   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19639
19640   return NOOP;
19641 }
19642
19643 /// LowerOperation - Provide custom lowering hooks for some operations.
19644 ///
19645 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19646   switch (Op.getOpcode()) {
19647   default: llvm_unreachable("Should not custom lower this!");
19648   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19649   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19650     return LowerCMP_SWAP(Op, Subtarget, DAG);
19651   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19652   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19653   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19654   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19655   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19656   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19657   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19658   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19659   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19660   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19661   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19662   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19663   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19664   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19665   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19666   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19667   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19668   case ISD::SHL_PARTS:
19669   case ISD::SRA_PARTS:
19670   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19671   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19672   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19673   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19674   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19675   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19676   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19677   case ISD::SIGN_EXTEND_VECTOR_INREG:
19678     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19679   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19680   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19681   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19682   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19683   case ISD::FABS:
19684   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19685   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19686   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19687   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19688   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19689   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19690   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19691   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19692   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19693   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19694   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19695   case ISD::INTRINSIC_VOID:
19696   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19697   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19698   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19699   case ISD::FRAME_TO_ARGS_OFFSET:
19700                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19701   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19702   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19703   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19704   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19705   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19706   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19707   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19708   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
19709   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19710   case ISD::CTTZ:
19711   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19712   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19713   case ISD::UMUL_LOHI:
19714   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19715   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
19716   case ISD::SRA:
19717   case ISD::SRL:
19718   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19719   case ISD::SADDO:
19720   case ISD::UADDO:
19721   case ISD::SSUBO:
19722   case ISD::USUBO:
19723   case ISD::SMULO:
19724   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19725   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19726   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19727   case ISD::ADDC:
19728   case ISD::ADDE:
19729   case ISD::SUBC:
19730   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19731   case ISD::ADD:                return LowerADD(Op, DAG);
19732   case ISD::SUB:                return LowerSUB(Op, DAG);
19733   case ISD::SMAX:
19734   case ISD::SMIN:
19735   case ISD::UMAX:
19736   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19737   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19738   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19739   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19740   case ISD::GC_TRANSITION_START:
19741                                 return LowerGC_TRANSITION_START(Op, DAG);
19742   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19743   }
19744 }
19745
19746 /// ReplaceNodeResults - Replace a node with an illegal result type
19747 /// with a new node built out of custom code.
19748 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19749                                            SmallVectorImpl<SDValue>&Results,
19750                                            SelectionDAG &DAG) const {
19751   SDLoc dl(N);
19752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19753   switch (N->getOpcode()) {
19754   default:
19755     llvm_unreachable("Do not know how to custom type legalize this operation!");
19756   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19757   case X86ISD::FMINC:
19758   case X86ISD::FMIN:
19759   case X86ISD::FMAXC:
19760   case X86ISD::FMAX: {
19761     EVT VT = N->getValueType(0);
19762     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
19763     SDValue UNDEF = DAG.getUNDEF(VT);
19764     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19765                               N->getOperand(0), UNDEF);
19766     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19767                               N->getOperand(1), UNDEF);
19768     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19769     return;
19770   }
19771   case ISD::SIGN_EXTEND_INREG:
19772   case ISD::ADDC:
19773   case ISD::ADDE:
19774   case ISD::SUBC:
19775   case ISD::SUBE:
19776     // We don't want to expand or promote these.
19777     return;
19778   case ISD::SDIV:
19779   case ISD::UDIV:
19780   case ISD::SREM:
19781   case ISD::UREM:
19782   case ISD::SDIVREM:
19783   case ISD::UDIVREM: {
19784     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19785     Results.push_back(V);
19786     return;
19787   }
19788   case ISD::FP_TO_SINT:
19789   case ISD::FP_TO_UINT: {
19790     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19791
19792     std::pair<SDValue,SDValue> Vals =
19793         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19794     SDValue FIST = Vals.first, StackSlot = Vals.second;
19795     if (FIST.getNode()) {
19796       EVT VT = N->getValueType(0);
19797       // Return a load from the stack slot.
19798       if (StackSlot.getNode())
19799         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19800                                       MachinePointerInfo(),
19801                                       false, false, false, 0));
19802       else
19803         Results.push_back(FIST);
19804     }
19805     return;
19806   }
19807   case ISD::UINT_TO_FP: {
19808     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19809     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19810         N->getValueType(0) != MVT::v2f32)
19811       return;
19812     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19813                                  N->getOperand(0));
19814     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19815                                      MVT::f64);
19816     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19817     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19818                              DAG.getBitcast(MVT::v2i64, VBias));
19819     Or = DAG.getBitcast(MVT::v2f64, Or);
19820     // TODO: Are there any fast-math-flags to propagate here?
19821     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19822     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19823     return;
19824   }
19825   case ISD::FP_ROUND: {
19826     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19827         return;
19828     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19829     Results.push_back(V);
19830     return;
19831   }
19832   case ISD::FP_EXTEND: {
19833     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19834     // No other ValueType for FP_EXTEND should reach this point.
19835     assert(N->getValueType(0) == MVT::v2f32 &&
19836            "Do not know how to legalize this Node");
19837     return;
19838   }
19839   case ISD::INTRINSIC_W_CHAIN: {
19840     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19841     switch (IntNo) {
19842     default : llvm_unreachable("Do not know how to custom type "
19843                                "legalize this intrinsic operation!");
19844     case Intrinsic::x86_rdtsc:
19845       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19846                                      Results);
19847     case Intrinsic::x86_rdtscp:
19848       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19849                                      Results);
19850     case Intrinsic::x86_rdpmc:
19851       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19852     }
19853   }
19854   case ISD::READCYCLECOUNTER: {
19855     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19856                                    Results);
19857   }
19858   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19859     EVT T = N->getValueType(0);
19860     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19861     bool Regs64bit = T == MVT::i128;
19862     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19863     SDValue cpInL, cpInH;
19864     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19865                         DAG.getConstant(0, dl, HalfT));
19866     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19867                         DAG.getConstant(1, dl, HalfT));
19868     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19869                              Regs64bit ? X86::RAX : X86::EAX,
19870                              cpInL, SDValue());
19871     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19872                              Regs64bit ? X86::RDX : X86::EDX,
19873                              cpInH, cpInL.getValue(1));
19874     SDValue swapInL, swapInH;
19875     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19876                           DAG.getConstant(0, dl, HalfT));
19877     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19878                           DAG.getConstant(1, dl, HalfT));
19879     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19880                                Regs64bit ? X86::RBX : X86::EBX,
19881                                swapInL, cpInH.getValue(1));
19882     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19883                                Regs64bit ? X86::RCX : X86::ECX,
19884                                swapInH, swapInL.getValue(1));
19885     SDValue Ops[] = { swapInH.getValue(0),
19886                       N->getOperand(1),
19887                       swapInH.getValue(1) };
19888     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19889     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19890     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19891                                   X86ISD::LCMPXCHG8_DAG;
19892     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19893     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19894                                         Regs64bit ? X86::RAX : X86::EAX,
19895                                         HalfT, Result.getValue(1));
19896     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19897                                         Regs64bit ? X86::RDX : X86::EDX,
19898                                         HalfT, cpOutL.getValue(2));
19899     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19900
19901     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19902                                         MVT::i32, cpOutH.getValue(2));
19903     SDValue Success =
19904         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19905                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19906     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19907
19908     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19909     Results.push_back(Success);
19910     Results.push_back(EFLAGS.getValue(1));
19911     return;
19912   }
19913   case ISD::ATOMIC_SWAP:
19914   case ISD::ATOMIC_LOAD_ADD:
19915   case ISD::ATOMIC_LOAD_SUB:
19916   case ISD::ATOMIC_LOAD_AND:
19917   case ISD::ATOMIC_LOAD_OR:
19918   case ISD::ATOMIC_LOAD_XOR:
19919   case ISD::ATOMIC_LOAD_NAND:
19920   case ISD::ATOMIC_LOAD_MIN:
19921   case ISD::ATOMIC_LOAD_MAX:
19922   case ISD::ATOMIC_LOAD_UMIN:
19923   case ISD::ATOMIC_LOAD_UMAX:
19924   case ISD::ATOMIC_LOAD: {
19925     // Delegate to generic TypeLegalization. Situations we can really handle
19926     // should have already been dealt with by AtomicExpandPass.cpp.
19927     break;
19928   }
19929   case ISD::BITCAST: {
19930     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19931     EVT DstVT = N->getValueType(0);
19932     EVT SrcVT = N->getOperand(0)->getValueType(0);
19933
19934     if (SrcVT != MVT::f64 ||
19935         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19936       return;
19937
19938     unsigned NumElts = DstVT.getVectorNumElements();
19939     EVT SVT = DstVT.getVectorElementType();
19940     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19941     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19942                                    MVT::v2f64, N->getOperand(0));
19943     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19944
19945     if (ExperimentalVectorWideningLegalization) {
19946       // If we are legalizing vectors by widening, we already have the desired
19947       // legal vector type, just return it.
19948       Results.push_back(ToVecInt);
19949       return;
19950     }
19951
19952     SmallVector<SDValue, 8> Elts;
19953     for (unsigned i = 0, e = NumElts; i != e; ++i)
19954       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19955                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19956
19957     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19958   }
19959   }
19960 }
19961
19962 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19963   switch ((X86ISD::NodeType)Opcode) {
19964   case X86ISD::FIRST_NUMBER:       break;
19965   case X86ISD::BSF:                return "X86ISD::BSF";
19966   case X86ISD::BSR:                return "X86ISD::BSR";
19967   case X86ISD::SHLD:               return "X86ISD::SHLD";
19968   case X86ISD::SHRD:               return "X86ISD::SHRD";
19969   case X86ISD::FAND:               return "X86ISD::FAND";
19970   case X86ISD::FANDN:              return "X86ISD::FANDN";
19971   case X86ISD::FOR:                return "X86ISD::FOR";
19972   case X86ISD::FXOR:               return "X86ISD::FXOR";
19973   case X86ISD::FILD:               return "X86ISD::FILD";
19974   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19975   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19976   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19977   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19978   case X86ISD::FLD:                return "X86ISD::FLD";
19979   case X86ISD::FST:                return "X86ISD::FST";
19980   case X86ISD::CALL:               return "X86ISD::CALL";
19981   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19982   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19983   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19984   case X86ISD::BT:                 return "X86ISD::BT";
19985   case X86ISD::CMP:                return "X86ISD::CMP";
19986   case X86ISD::COMI:               return "X86ISD::COMI";
19987   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19988   case X86ISD::CMPM:               return "X86ISD::CMPM";
19989   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19990   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19991   case X86ISD::SETCC:              return "X86ISD::SETCC";
19992   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19993   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19994   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19995   case X86ISD::CMOV:               return "X86ISD::CMOV";
19996   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19997   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19998   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19999   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20000   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20001   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20002   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20003   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20004   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20005   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20006   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20007   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20008   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20009   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20010   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20011   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20012   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20013   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20014   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20015   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20016   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20017   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20018   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20019   case X86ISD::HADD:               return "X86ISD::HADD";
20020   case X86ISD::HSUB:               return "X86ISD::HSUB";
20021   case X86ISD::FHADD:              return "X86ISD::FHADD";
20022   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20023   case X86ISD::ABS:                return "X86ISD::ABS";
20024   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20025   case X86ISD::FMAX:               return "X86ISD::FMAX";
20026   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20027   case X86ISD::FMIN:               return "X86ISD::FMIN";
20028   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20029   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20030   case X86ISD::FMINC:              return "X86ISD::FMINC";
20031   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20032   case X86ISD::FRCP:               return "X86ISD::FRCP";
20033   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20034   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20035   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20036   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20037   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20038   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20039   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20040   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20041   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20042   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20043   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20044   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20045   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20046   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20047   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20048   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20049   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20050   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20051   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20052   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20053   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20054   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20055   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20056   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20057   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20058   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20059   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20060   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20061   case X86ISD::VSHL:               return "X86ISD::VSHL";
20062   case X86ISD::VSRL:               return "X86ISD::VSRL";
20063   case X86ISD::VSRA:               return "X86ISD::VSRA";
20064   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20065   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20066   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20067   case X86ISD::CMPP:               return "X86ISD::CMPP";
20068   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20069   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20070   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20071   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20072   case X86ISD::ADD:                return "X86ISD::ADD";
20073   case X86ISD::SUB:                return "X86ISD::SUB";
20074   case X86ISD::ADC:                return "X86ISD::ADC";
20075   case X86ISD::SBB:                return "X86ISD::SBB";
20076   case X86ISD::SMUL:               return "X86ISD::SMUL";
20077   case X86ISD::UMUL:               return "X86ISD::UMUL";
20078   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20079   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20080   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20081   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20082   case X86ISD::INC:                return "X86ISD::INC";
20083   case X86ISD::DEC:                return "X86ISD::DEC";
20084   case X86ISD::OR:                 return "X86ISD::OR";
20085   case X86ISD::XOR:                return "X86ISD::XOR";
20086   case X86ISD::AND:                return "X86ISD::AND";
20087   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20088   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20089   case X86ISD::PTEST:              return "X86ISD::PTEST";
20090   case X86ISD::TESTP:              return "X86ISD::TESTP";
20091   case X86ISD::TESTM:              return "X86ISD::TESTM";
20092   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20093   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20094   case X86ISD::KTEST:              return "X86ISD::KTEST";
20095   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20096   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20097   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20098   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20099   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20100   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20101   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20102   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20103   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20104   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20105   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20106   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20107   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20108   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20109   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20110   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20111   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20112   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20113   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20114   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20115   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20116   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20117   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20118   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20119   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20120   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20121   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20122   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20123   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20124   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20125   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20126   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20127   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20128   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20129   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20130   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20131   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20132   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20133   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20134   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20135   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20136   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20137   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20138   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20139   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20140   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20141   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20142   case X86ISD::SAHF:               return "X86ISD::SAHF";
20143   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20144   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20145   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20146   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20147   case X86ISD::VPROT:              return "X86ISD::VPROT";
20148   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20149   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20150   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20151   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20152   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20153   case X86ISD::FMADD:              return "X86ISD::FMADD";
20154   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20155   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20156   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20157   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20158   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20159   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20160   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20161   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20162   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20163   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20164   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20165   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20166   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20167   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20168   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20169   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20170   case X86ISD::XTEST:              return "X86ISD::XTEST";
20171   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20172   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20173   case X86ISD::SELECT:             return "X86ISD::SELECT";
20174   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20175   case X86ISD::RCP28:              return "X86ISD::RCP28";
20176   case X86ISD::EXP2:               return "X86ISD::EXP2";
20177   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20178   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20179   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20180   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20181   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20182   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20183   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20184   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20185   case X86ISD::ADDS:               return "X86ISD::ADDS";
20186   case X86ISD::SUBS:               return "X86ISD::SUBS";
20187   case X86ISD::AVG:                return "X86ISD::AVG";
20188   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20189   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20190   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20191   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20192   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20193   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20194   }
20195   return nullptr;
20196 }
20197
20198 // isLegalAddressingMode - Return true if the addressing mode represented
20199 // by AM is legal for this target, for a load/store of the specified type.
20200 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20201                                               const AddrMode &AM, Type *Ty,
20202                                               unsigned AS) const {
20203   // X86 supports extremely general addressing modes.
20204   CodeModel::Model M = getTargetMachine().getCodeModel();
20205   Reloc::Model R = getTargetMachine().getRelocationModel();
20206
20207   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20208   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20209     return false;
20210
20211   if (AM.BaseGV) {
20212     unsigned GVFlags =
20213       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20214
20215     // If a reference to this global requires an extra load, we can't fold it.
20216     if (isGlobalStubReference(GVFlags))
20217       return false;
20218
20219     // If BaseGV requires a register for the PIC base, we cannot also have a
20220     // BaseReg specified.
20221     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20222       return false;
20223
20224     // If lower 4G is not available, then we must use rip-relative addressing.
20225     if ((M != CodeModel::Small || R != Reloc::Static) &&
20226         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20227       return false;
20228   }
20229
20230   switch (AM.Scale) {
20231   case 0:
20232   case 1:
20233   case 2:
20234   case 4:
20235   case 8:
20236     // These scales always work.
20237     break;
20238   case 3:
20239   case 5:
20240   case 9:
20241     // These scales are formed with basereg+scalereg.  Only accept if there is
20242     // no basereg yet.
20243     if (AM.HasBaseReg)
20244       return false;
20245     break;
20246   default:  // Other stuff never works.
20247     return false;
20248   }
20249
20250   return true;
20251 }
20252
20253 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20254   unsigned Bits = Ty->getScalarSizeInBits();
20255
20256   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20257   // particularly cheaper than those without.
20258   if (Bits == 8)
20259     return false;
20260
20261   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20262   // variable shifts just as cheap as scalar ones.
20263   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20264     return false;
20265
20266   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20267   // fully general vector.
20268   return true;
20269 }
20270
20271 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20272   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20273     return false;
20274   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20275   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20276   return NumBits1 > NumBits2;
20277 }
20278
20279 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20280   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20281     return false;
20282
20283   if (!isTypeLegal(EVT::getEVT(Ty1)))
20284     return false;
20285
20286   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20287
20288   // Assuming the caller doesn't have a zeroext or signext return parameter,
20289   // truncation all the way down to i1 is valid.
20290   return true;
20291 }
20292
20293 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20294   return isInt<32>(Imm);
20295 }
20296
20297 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20298   // Can also use sub to handle negated immediates.
20299   return isInt<32>(Imm);
20300 }
20301
20302 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20303   if (!VT1.isInteger() || !VT2.isInteger())
20304     return false;
20305   unsigned NumBits1 = VT1.getSizeInBits();
20306   unsigned NumBits2 = VT2.getSizeInBits();
20307   return NumBits1 > NumBits2;
20308 }
20309
20310 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20311   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20312   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20313 }
20314
20315 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20316   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20317   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20318 }
20319
20320 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20321   EVT VT1 = Val.getValueType();
20322   if (isZExtFree(VT1, VT2))
20323     return true;
20324
20325   if (Val.getOpcode() != ISD::LOAD)
20326     return false;
20327
20328   if (!VT1.isSimple() || !VT1.isInteger() ||
20329       !VT2.isSimple() || !VT2.isInteger())
20330     return false;
20331
20332   switch (VT1.getSimpleVT().SimpleTy) {
20333   default: break;
20334   case MVT::i8:
20335   case MVT::i16:
20336   case MVT::i32:
20337     // X86 has 8, 16, and 32-bit zero-extending loads.
20338     return true;
20339   }
20340
20341   return false;
20342 }
20343
20344 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20345
20346 bool
20347 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20348   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20349     return false;
20350
20351   VT = VT.getScalarType();
20352
20353   if (!VT.isSimple())
20354     return false;
20355
20356   switch (VT.getSimpleVT().SimpleTy) {
20357   case MVT::f32:
20358   case MVT::f64:
20359     return true;
20360   default:
20361     break;
20362   }
20363
20364   return false;
20365 }
20366
20367 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20368   // i16 instructions are longer (0x66 prefix) and potentially slower.
20369   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20370 }
20371
20372 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20373 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20374 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20375 /// are assumed to be legal.
20376 bool
20377 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20378                                       EVT VT) const {
20379   if (!VT.isSimple())
20380     return false;
20381
20382   // Not for i1 vectors
20383   if (VT.getSimpleVT().getScalarType() == MVT::i1)
20384     return false;
20385
20386   // Very little shuffling can be done for 64-bit vectors right now.
20387   if (VT.getSimpleVT().getSizeInBits() == 64)
20388     return false;
20389
20390   // We only care that the types being shuffled are legal. The lowering can
20391   // handle any possible shuffle mask that results.
20392   return isTypeLegal(VT.getSimpleVT());
20393 }
20394
20395 bool
20396 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20397                                           EVT VT) const {
20398   // Just delegate to the generic legality, clear masks aren't special.
20399   return isShuffleMaskLegal(Mask, VT);
20400 }
20401
20402 //===----------------------------------------------------------------------===//
20403 //                           X86 Scheduler Hooks
20404 //===----------------------------------------------------------------------===//
20405
20406 /// Utility function to emit xbegin specifying the start of an RTM region.
20407 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20408                                      const TargetInstrInfo *TII) {
20409   DebugLoc DL = MI->getDebugLoc();
20410
20411   const BasicBlock *BB = MBB->getBasicBlock();
20412   MachineFunction::iterator I = ++MBB->getIterator();
20413
20414   // For the v = xbegin(), we generate
20415   //
20416   // thisMBB:
20417   //  xbegin sinkMBB
20418   //
20419   // mainMBB:
20420   //  eax = -1
20421   //
20422   // sinkMBB:
20423   //  v = eax
20424
20425   MachineBasicBlock *thisMBB = MBB;
20426   MachineFunction *MF = MBB->getParent();
20427   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20428   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20429   MF->insert(I, mainMBB);
20430   MF->insert(I, sinkMBB);
20431
20432   // Transfer the remainder of BB and its successor edges to sinkMBB.
20433   sinkMBB->splice(sinkMBB->begin(), MBB,
20434                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20435   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20436
20437   // thisMBB:
20438   //  xbegin sinkMBB
20439   //  # fallthrough to mainMBB
20440   //  # abortion to sinkMBB
20441   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20442   thisMBB->addSuccessor(mainMBB);
20443   thisMBB->addSuccessor(sinkMBB);
20444
20445   // mainMBB:
20446   //  EAX = -1
20447   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20448   mainMBB->addSuccessor(sinkMBB);
20449
20450   // sinkMBB:
20451   // EAX is live into the sinkMBB
20452   sinkMBB->addLiveIn(X86::EAX);
20453   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20454           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20455     .addReg(X86::EAX);
20456
20457   MI->eraseFromParent();
20458   return sinkMBB;
20459 }
20460
20461 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20462 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20463 // in the .td file.
20464 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20465                                        const TargetInstrInfo *TII) {
20466   unsigned Opc;
20467   switch (MI->getOpcode()) {
20468   default: llvm_unreachable("illegal opcode!");
20469   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20470   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20471   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20472   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20473   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20474   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20475   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20476   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20477   }
20478
20479   DebugLoc dl = MI->getDebugLoc();
20480   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20481
20482   unsigned NumArgs = MI->getNumOperands();
20483   for (unsigned i = 1; i < NumArgs; ++i) {
20484     MachineOperand &Op = MI->getOperand(i);
20485     if (!(Op.isReg() && Op.isImplicit()))
20486       MIB.addOperand(Op);
20487   }
20488   if (MI->hasOneMemOperand())
20489     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20490
20491   BuildMI(*BB, MI, dl,
20492     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20493     .addReg(X86::XMM0);
20494
20495   MI->eraseFromParent();
20496   return BB;
20497 }
20498
20499 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20500 // defs in an instruction pattern
20501 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20502                                        const TargetInstrInfo *TII) {
20503   unsigned Opc;
20504   switch (MI->getOpcode()) {
20505   default: llvm_unreachable("illegal opcode!");
20506   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20507   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20508   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20509   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20510   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20511   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20512   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20513   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20514   }
20515
20516   DebugLoc dl = MI->getDebugLoc();
20517   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20518
20519   unsigned NumArgs = MI->getNumOperands(); // remove the results
20520   for (unsigned i = 1; i < NumArgs; ++i) {
20521     MachineOperand &Op = MI->getOperand(i);
20522     if (!(Op.isReg() && Op.isImplicit()))
20523       MIB.addOperand(Op);
20524   }
20525   if (MI->hasOneMemOperand())
20526     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20527
20528   BuildMI(*BB, MI, dl,
20529     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20530     .addReg(X86::ECX);
20531
20532   MI->eraseFromParent();
20533   return BB;
20534 }
20535
20536 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20537                                       const X86Subtarget *Subtarget) {
20538   DebugLoc dl = MI->getDebugLoc();
20539   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20540   // Address into RAX/EAX, other two args into ECX, EDX.
20541   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20542   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20543   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20544   for (int i = 0; i < X86::AddrNumOperands; ++i)
20545     MIB.addOperand(MI->getOperand(i));
20546
20547   unsigned ValOps = X86::AddrNumOperands;
20548   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20549     .addReg(MI->getOperand(ValOps).getReg());
20550   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20551     .addReg(MI->getOperand(ValOps+1).getReg());
20552
20553   // The instruction doesn't actually take any operands though.
20554   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20555
20556   MI->eraseFromParent(); // The pseudo is gone now.
20557   return BB;
20558 }
20559
20560 MachineBasicBlock *
20561 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20562                                                  MachineBasicBlock *MBB) const {
20563   // Emit va_arg instruction on X86-64.
20564
20565   // Operands to this pseudo-instruction:
20566   // 0  ) Output        : destination address (reg)
20567   // 1-5) Input         : va_list address (addr, i64mem)
20568   // 6  ) ArgSize       : Size (in bytes) of vararg type
20569   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20570   // 8  ) Align         : Alignment of type
20571   // 9  ) EFLAGS (implicit-def)
20572
20573   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20574   static_assert(X86::AddrNumOperands == 5,
20575                 "VAARG_64 assumes 5 address operands");
20576
20577   unsigned DestReg = MI->getOperand(0).getReg();
20578   MachineOperand &Base = MI->getOperand(1);
20579   MachineOperand &Scale = MI->getOperand(2);
20580   MachineOperand &Index = MI->getOperand(3);
20581   MachineOperand &Disp = MI->getOperand(4);
20582   MachineOperand &Segment = MI->getOperand(5);
20583   unsigned ArgSize = MI->getOperand(6).getImm();
20584   unsigned ArgMode = MI->getOperand(7).getImm();
20585   unsigned Align = MI->getOperand(8).getImm();
20586
20587   // Memory Reference
20588   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20589   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20590   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20591
20592   // Machine Information
20593   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20594   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20595   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20596   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20597   DebugLoc DL = MI->getDebugLoc();
20598
20599   // struct va_list {
20600   //   i32   gp_offset
20601   //   i32   fp_offset
20602   //   i64   overflow_area (address)
20603   //   i64   reg_save_area (address)
20604   // }
20605   // sizeof(va_list) = 24
20606   // alignment(va_list) = 8
20607
20608   unsigned TotalNumIntRegs = 6;
20609   unsigned TotalNumXMMRegs = 8;
20610   bool UseGPOffset = (ArgMode == 1);
20611   bool UseFPOffset = (ArgMode == 2);
20612   unsigned MaxOffset = TotalNumIntRegs * 8 +
20613                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20614
20615   /* Align ArgSize to a multiple of 8 */
20616   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20617   bool NeedsAlign = (Align > 8);
20618
20619   MachineBasicBlock *thisMBB = MBB;
20620   MachineBasicBlock *overflowMBB;
20621   MachineBasicBlock *offsetMBB;
20622   MachineBasicBlock *endMBB;
20623
20624   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20625   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20626   unsigned OffsetReg = 0;
20627
20628   if (!UseGPOffset && !UseFPOffset) {
20629     // If we only pull from the overflow region, we don't create a branch.
20630     // We don't need to alter control flow.
20631     OffsetDestReg = 0; // unused
20632     OverflowDestReg = DestReg;
20633
20634     offsetMBB = nullptr;
20635     overflowMBB = thisMBB;
20636     endMBB = thisMBB;
20637   } else {
20638     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20639     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20640     // If not, pull from overflow_area. (branch to overflowMBB)
20641     //
20642     //       thisMBB
20643     //         |     .
20644     //         |        .
20645     //     offsetMBB   overflowMBB
20646     //         |        .
20647     //         |     .
20648     //        endMBB
20649
20650     // Registers for the PHI in endMBB
20651     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20652     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20653
20654     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20655     MachineFunction *MF = MBB->getParent();
20656     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20657     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20658     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20659
20660     MachineFunction::iterator MBBIter = ++MBB->getIterator();
20661
20662     // Insert the new basic blocks
20663     MF->insert(MBBIter, offsetMBB);
20664     MF->insert(MBBIter, overflowMBB);
20665     MF->insert(MBBIter, endMBB);
20666
20667     // Transfer the remainder of MBB and its successor edges to endMBB.
20668     endMBB->splice(endMBB->begin(), thisMBB,
20669                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20670     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20671
20672     // Make offsetMBB and overflowMBB successors of thisMBB
20673     thisMBB->addSuccessor(offsetMBB);
20674     thisMBB->addSuccessor(overflowMBB);
20675
20676     // endMBB is a successor of both offsetMBB and overflowMBB
20677     offsetMBB->addSuccessor(endMBB);
20678     overflowMBB->addSuccessor(endMBB);
20679
20680     // Load the offset value into a register
20681     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20682     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20683       .addOperand(Base)
20684       .addOperand(Scale)
20685       .addOperand(Index)
20686       .addDisp(Disp, UseFPOffset ? 4 : 0)
20687       .addOperand(Segment)
20688       .setMemRefs(MMOBegin, MMOEnd);
20689
20690     // Check if there is enough room left to pull this argument.
20691     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20692       .addReg(OffsetReg)
20693       .addImm(MaxOffset + 8 - ArgSizeA8);
20694
20695     // Branch to "overflowMBB" if offset >= max
20696     // Fall through to "offsetMBB" otherwise
20697     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20698       .addMBB(overflowMBB);
20699   }
20700
20701   // In offsetMBB, emit code to use the reg_save_area.
20702   if (offsetMBB) {
20703     assert(OffsetReg != 0);
20704
20705     // Read the reg_save_area address.
20706     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20707     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20708       .addOperand(Base)
20709       .addOperand(Scale)
20710       .addOperand(Index)
20711       .addDisp(Disp, 16)
20712       .addOperand(Segment)
20713       .setMemRefs(MMOBegin, MMOEnd);
20714
20715     // Zero-extend the offset
20716     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20717       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20718         .addImm(0)
20719         .addReg(OffsetReg)
20720         .addImm(X86::sub_32bit);
20721
20722     // Add the offset to the reg_save_area to get the final address.
20723     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20724       .addReg(OffsetReg64)
20725       .addReg(RegSaveReg);
20726
20727     // Compute the offset for the next argument
20728     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20729     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20730       .addReg(OffsetReg)
20731       .addImm(UseFPOffset ? 16 : 8);
20732
20733     // Store it back into the va_list.
20734     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20735       .addOperand(Base)
20736       .addOperand(Scale)
20737       .addOperand(Index)
20738       .addDisp(Disp, UseFPOffset ? 4 : 0)
20739       .addOperand(Segment)
20740       .addReg(NextOffsetReg)
20741       .setMemRefs(MMOBegin, MMOEnd);
20742
20743     // Jump to endMBB
20744     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20745       .addMBB(endMBB);
20746   }
20747
20748   //
20749   // Emit code to use overflow area
20750   //
20751
20752   // Load the overflow_area address into a register.
20753   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20754   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20755     .addOperand(Base)
20756     .addOperand(Scale)
20757     .addOperand(Index)
20758     .addDisp(Disp, 8)
20759     .addOperand(Segment)
20760     .setMemRefs(MMOBegin, MMOEnd);
20761
20762   // If we need to align it, do so. Otherwise, just copy the address
20763   // to OverflowDestReg.
20764   if (NeedsAlign) {
20765     // Align the overflow address
20766     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20767     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20768
20769     // aligned_addr = (addr + (align-1)) & ~(align-1)
20770     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20771       .addReg(OverflowAddrReg)
20772       .addImm(Align-1);
20773
20774     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20775       .addReg(TmpReg)
20776       .addImm(~(uint64_t)(Align-1));
20777   } else {
20778     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20779       .addReg(OverflowAddrReg);
20780   }
20781
20782   // Compute the next overflow address after this argument.
20783   // (the overflow address should be kept 8-byte aligned)
20784   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20785   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20786     .addReg(OverflowDestReg)
20787     .addImm(ArgSizeA8);
20788
20789   // Store the new overflow address.
20790   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20791     .addOperand(Base)
20792     .addOperand(Scale)
20793     .addOperand(Index)
20794     .addDisp(Disp, 8)
20795     .addOperand(Segment)
20796     .addReg(NextAddrReg)
20797     .setMemRefs(MMOBegin, MMOEnd);
20798
20799   // If we branched, emit the PHI to the front of endMBB.
20800   if (offsetMBB) {
20801     BuildMI(*endMBB, endMBB->begin(), DL,
20802             TII->get(X86::PHI), DestReg)
20803       .addReg(OffsetDestReg).addMBB(offsetMBB)
20804       .addReg(OverflowDestReg).addMBB(overflowMBB);
20805   }
20806
20807   // Erase the pseudo instruction
20808   MI->eraseFromParent();
20809
20810   return endMBB;
20811 }
20812
20813 MachineBasicBlock *
20814 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20815                                                  MachineInstr *MI,
20816                                                  MachineBasicBlock *MBB) const {
20817   // Emit code to save XMM registers to the stack. The ABI says that the
20818   // number of registers to save is given in %al, so it's theoretically
20819   // possible to do an indirect jump trick to avoid saving all of them,
20820   // however this code takes a simpler approach and just executes all
20821   // of the stores if %al is non-zero. It's less code, and it's probably
20822   // easier on the hardware branch predictor, and stores aren't all that
20823   // expensive anyway.
20824
20825   // Create the new basic blocks. One block contains all the XMM stores,
20826   // and one block is the final destination regardless of whether any
20827   // stores were performed.
20828   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20829   MachineFunction *F = MBB->getParent();
20830   MachineFunction::iterator MBBIter = ++MBB->getIterator();
20831   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20832   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20833   F->insert(MBBIter, XMMSaveMBB);
20834   F->insert(MBBIter, EndMBB);
20835
20836   // Transfer the remainder of MBB and its successor edges to EndMBB.
20837   EndMBB->splice(EndMBB->begin(), MBB,
20838                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20839   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20840
20841   // The original block will now fall through to the XMM save block.
20842   MBB->addSuccessor(XMMSaveMBB);
20843   // The XMMSaveMBB will fall through to the end block.
20844   XMMSaveMBB->addSuccessor(EndMBB);
20845
20846   // Now add the instructions.
20847   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20848   DebugLoc DL = MI->getDebugLoc();
20849
20850   unsigned CountReg = MI->getOperand(0).getReg();
20851   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20852   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20853
20854   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20855     // If %al is 0, branch around the XMM save block.
20856     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20857     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20858     MBB->addSuccessor(EndMBB);
20859   }
20860
20861   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20862   // that was just emitted, but clearly shouldn't be "saved".
20863   assert((MI->getNumOperands() <= 3 ||
20864           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20865           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20866          && "Expected last argument to be EFLAGS");
20867   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20868   // In the XMM save block, save all the XMM argument registers.
20869   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20870     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20871     MachineMemOperand *MMO = F->getMachineMemOperand(
20872         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20873         MachineMemOperand::MOStore,
20874         /*Size=*/16, /*Align=*/16);
20875     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20876       .addFrameIndex(RegSaveFrameIndex)
20877       .addImm(/*Scale=*/1)
20878       .addReg(/*IndexReg=*/0)
20879       .addImm(/*Disp=*/Offset)
20880       .addReg(/*Segment=*/0)
20881       .addReg(MI->getOperand(i).getReg())
20882       .addMemOperand(MMO);
20883   }
20884
20885   MI->eraseFromParent();   // The pseudo instruction is gone now.
20886
20887   return EndMBB;
20888 }
20889
20890 // The EFLAGS operand of SelectItr might be missing a kill marker
20891 // because there were multiple uses of EFLAGS, and ISel didn't know
20892 // which to mark. Figure out whether SelectItr should have had a
20893 // kill marker, and set it if it should. Returns the correct kill
20894 // marker value.
20895 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20896                                      MachineBasicBlock* BB,
20897                                      const TargetRegisterInfo* TRI) {
20898   // Scan forward through BB for a use/def of EFLAGS.
20899   MachineBasicBlock::iterator miI(std::next(SelectItr));
20900   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20901     const MachineInstr& mi = *miI;
20902     if (mi.readsRegister(X86::EFLAGS))
20903       return false;
20904     if (mi.definesRegister(X86::EFLAGS))
20905       break; // Should have kill-flag - update below.
20906   }
20907
20908   // If we hit the end of the block, check whether EFLAGS is live into a
20909   // successor.
20910   if (miI == BB->end()) {
20911     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20912                                           sEnd = BB->succ_end();
20913          sItr != sEnd; ++sItr) {
20914       MachineBasicBlock* succ = *sItr;
20915       if (succ->isLiveIn(X86::EFLAGS))
20916         return false;
20917     }
20918   }
20919
20920   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20921   // out. SelectMI should have a kill flag on EFLAGS.
20922   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20923   return true;
20924 }
20925
20926 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20927 // together with other CMOV pseudo-opcodes into a single basic-block with
20928 // conditional jump around it.
20929 static bool isCMOVPseudo(MachineInstr *MI) {
20930   switch (MI->getOpcode()) {
20931   case X86::CMOV_FR32:
20932   case X86::CMOV_FR64:
20933   case X86::CMOV_GR8:
20934   case X86::CMOV_GR16:
20935   case X86::CMOV_GR32:
20936   case X86::CMOV_RFP32:
20937   case X86::CMOV_RFP64:
20938   case X86::CMOV_RFP80:
20939   case X86::CMOV_V2F64:
20940   case X86::CMOV_V2I64:
20941   case X86::CMOV_V4F32:
20942   case X86::CMOV_V4F64:
20943   case X86::CMOV_V4I64:
20944   case X86::CMOV_V16F32:
20945   case X86::CMOV_V8F32:
20946   case X86::CMOV_V8F64:
20947   case X86::CMOV_V8I64:
20948   case X86::CMOV_V8I1:
20949   case X86::CMOV_V16I1:
20950   case X86::CMOV_V32I1:
20951   case X86::CMOV_V64I1:
20952     return true;
20953
20954   default:
20955     return false;
20956   }
20957 }
20958
20959 MachineBasicBlock *
20960 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20961                                      MachineBasicBlock *BB) const {
20962   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20963   DebugLoc DL = MI->getDebugLoc();
20964
20965   // To "insert" a SELECT_CC instruction, we actually have to insert the
20966   // diamond control-flow pattern.  The incoming instruction knows the
20967   // destination vreg to set, the condition code register to branch on, the
20968   // true/false values to select between, and a branch opcode to use.
20969   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20970   MachineFunction::iterator It = ++BB->getIterator();
20971
20972   //  thisMBB:
20973   //  ...
20974   //   TrueVal = ...
20975   //   cmpTY ccX, r1, r2
20976   //   bCC copy1MBB
20977   //   fallthrough --> copy0MBB
20978   MachineBasicBlock *thisMBB = BB;
20979   MachineFunction *F = BB->getParent();
20980
20981   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20982   // as described above, by inserting a BB, and then making a PHI at the join
20983   // point to select the true and false operands of the CMOV in the PHI.
20984   //
20985   // The code also handles two different cases of multiple CMOV opcodes
20986   // in a row.
20987   //
20988   // Case 1:
20989   // In this case, there are multiple CMOVs in a row, all which are based on
20990   // the same condition setting (or the exact opposite condition setting).
20991   // In this case we can lower all the CMOVs using a single inserted BB, and
20992   // then make a number of PHIs at the join point to model the CMOVs. The only
20993   // trickiness here, is that in a case like:
20994   //
20995   // t2 = CMOV cond1 t1, f1
20996   // t3 = CMOV cond1 t2, f2
20997   //
20998   // when rewriting this into PHIs, we have to perform some renaming on the
20999   // temps since you cannot have a PHI operand refer to a PHI result earlier
21000   // in the same block.  The "simple" but wrong lowering would be:
21001   //
21002   // t2 = PHI t1(BB1), f1(BB2)
21003   // t3 = PHI t2(BB1), f2(BB2)
21004   //
21005   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21006   // renaming is to note that on the path through BB1, t2 is really just a
21007   // copy of t1, and do that renaming, properly generating:
21008   //
21009   // t2 = PHI t1(BB1), f1(BB2)
21010   // t3 = PHI t1(BB1), f2(BB2)
21011   //
21012   // Case 2, we lower cascaded CMOVs such as
21013   //
21014   //   (CMOV (CMOV F, T, cc1), T, cc2)
21015   //
21016   // to two successives branches.  For that, we look for another CMOV as the
21017   // following instruction.
21018   //
21019   // Without this, we would add a PHI between the two jumps, which ends up
21020   // creating a few copies all around. For instance, for
21021   //
21022   //    (sitofp (zext (fcmp une)))
21023   //
21024   // we would generate:
21025   //
21026   //         ucomiss %xmm1, %xmm0
21027   //         movss  <1.0f>, %xmm0
21028   //         movaps  %xmm0, %xmm1
21029   //         jne     .LBB5_2
21030   //         xorps   %xmm1, %xmm1
21031   // .LBB5_2:
21032   //         jp      .LBB5_4
21033   //         movaps  %xmm1, %xmm0
21034   // .LBB5_4:
21035   //         retq
21036   //
21037   // because this custom-inserter would have generated:
21038   //
21039   //   A
21040   //   | \
21041   //   |  B
21042   //   | /
21043   //   C
21044   //   | \
21045   //   |  D
21046   //   | /
21047   //   E
21048   //
21049   // A: X = ...; Y = ...
21050   // B: empty
21051   // C: Z = PHI [X, A], [Y, B]
21052   // D: empty
21053   // E: PHI [X, C], [Z, D]
21054   //
21055   // If we lower both CMOVs in a single step, we can instead generate:
21056   //
21057   //   A
21058   //   | \
21059   //   |  C
21060   //   | /|
21061   //   |/ |
21062   //   |  |
21063   //   |  D
21064   //   | /
21065   //   E
21066   //
21067   // A: X = ...; Y = ...
21068   // D: empty
21069   // E: PHI [X, A], [X, C], [Y, D]
21070   //
21071   // Which, in our sitofp/fcmp example, gives us something like:
21072   //
21073   //         ucomiss %xmm1, %xmm0
21074   //         movss  <1.0f>, %xmm0
21075   //         jne     .LBB5_4
21076   //         jp      .LBB5_4
21077   //         xorps   %xmm0, %xmm0
21078   // .LBB5_4:
21079   //         retq
21080   //
21081   MachineInstr *CascadedCMOV = nullptr;
21082   MachineInstr *LastCMOV = MI;
21083   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21084   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21085   MachineBasicBlock::iterator NextMIIt =
21086       std::next(MachineBasicBlock::iterator(MI));
21087
21088   // Check for case 1, where there are multiple CMOVs with the same condition
21089   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21090   // number of jumps the most.
21091
21092   if (isCMOVPseudo(MI)) {
21093     // See if we have a string of CMOVS with the same condition.
21094     while (NextMIIt != BB->end() &&
21095            isCMOVPseudo(NextMIIt) &&
21096            (NextMIIt->getOperand(3).getImm() == CC ||
21097             NextMIIt->getOperand(3).getImm() == OppCC)) {
21098       LastCMOV = &*NextMIIt;
21099       ++NextMIIt;
21100     }
21101   }
21102
21103   // This checks for case 2, but only do this if we didn't already find
21104   // case 1, as indicated by LastCMOV == MI.
21105   if (LastCMOV == MI &&
21106       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21107       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21108       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21109     CascadedCMOV = &*NextMIIt;
21110   }
21111
21112   MachineBasicBlock *jcc1MBB = nullptr;
21113
21114   // If we have a cascaded CMOV, we lower it to two successive branches to
21115   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21116   if (CascadedCMOV) {
21117     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21118     F->insert(It, jcc1MBB);
21119     jcc1MBB->addLiveIn(X86::EFLAGS);
21120   }
21121
21122   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21123   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21124   F->insert(It, copy0MBB);
21125   F->insert(It, sinkMBB);
21126
21127   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21128   // live into the sink and copy blocks.
21129   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21130
21131   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21132   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21133       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21134     copy0MBB->addLiveIn(X86::EFLAGS);
21135     sinkMBB->addLiveIn(X86::EFLAGS);
21136   }
21137
21138   // Transfer the remainder of BB and its successor edges to sinkMBB.
21139   sinkMBB->splice(sinkMBB->begin(), BB,
21140                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21141   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21142
21143   // Add the true and fallthrough blocks as its successors.
21144   if (CascadedCMOV) {
21145     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21146     BB->addSuccessor(jcc1MBB);
21147
21148     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21149     // jump to the sinkMBB.
21150     jcc1MBB->addSuccessor(copy0MBB);
21151     jcc1MBB->addSuccessor(sinkMBB);
21152   } else {
21153     BB->addSuccessor(copy0MBB);
21154   }
21155
21156   // The true block target of the first (or only) branch is always sinkMBB.
21157   BB->addSuccessor(sinkMBB);
21158
21159   // Create the conditional branch instruction.
21160   unsigned Opc = X86::GetCondBranchFromCond(CC);
21161   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21162
21163   if (CascadedCMOV) {
21164     unsigned Opc2 = X86::GetCondBranchFromCond(
21165         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21166     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21167   }
21168
21169   //  copy0MBB:
21170   //   %FalseValue = ...
21171   //   # fallthrough to sinkMBB
21172   copy0MBB->addSuccessor(sinkMBB);
21173
21174   //  sinkMBB:
21175   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21176   //  ...
21177   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21178   MachineBasicBlock::iterator MIItEnd =
21179     std::next(MachineBasicBlock::iterator(LastCMOV));
21180   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21181   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21182   MachineInstrBuilder MIB;
21183
21184   // As we are creating the PHIs, we have to be careful if there is more than
21185   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21186   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21187   // That also means that PHI construction must work forward from earlier to
21188   // later, and that the code must maintain a mapping from earlier PHI's
21189   // destination registers, and the registers that went into the PHI.
21190
21191   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21192     unsigned DestReg = MIIt->getOperand(0).getReg();
21193     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21194     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21195
21196     // If this CMOV we are generating is the opposite condition from
21197     // the jump we generated, then we have to swap the operands for the
21198     // PHI that is going to be generated.
21199     if (MIIt->getOperand(3).getImm() == OppCC)
21200         std::swap(Op1Reg, Op2Reg);
21201
21202     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21203       Op1Reg = RegRewriteTable[Op1Reg].first;
21204
21205     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21206       Op2Reg = RegRewriteTable[Op2Reg].second;
21207
21208     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21209                   TII->get(X86::PHI), DestReg)
21210           .addReg(Op1Reg).addMBB(copy0MBB)
21211           .addReg(Op2Reg).addMBB(thisMBB);
21212
21213     // Add this PHI to the rewrite table.
21214     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21215   }
21216
21217   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21218   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21219   if (CascadedCMOV) {
21220     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21221     // Copy the PHI result to the register defined by the second CMOV.
21222     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21223             DL, TII->get(TargetOpcode::COPY),
21224             CascadedCMOV->getOperand(0).getReg())
21225         .addReg(MI->getOperand(0).getReg());
21226     CascadedCMOV->eraseFromParent();
21227   }
21228
21229   // Now remove the CMOV(s).
21230   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21231     (MIIt++)->eraseFromParent();
21232
21233   return sinkMBB;
21234 }
21235
21236 MachineBasicBlock *
21237 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21238                                        MachineBasicBlock *BB) const {
21239   // Combine the following atomic floating-point modification pattern:
21240   //   a.store(reg OP a.load(acquire), release)
21241   // Transform them into:
21242   //   OPss (%gpr), %xmm
21243   //   movss %xmm, (%gpr)
21244   // Or sd equivalent for 64-bit operations.
21245   unsigned MOp, FOp;
21246   switch (MI->getOpcode()) {
21247   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21248   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21249   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21250   }
21251   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21252   DebugLoc DL = MI->getDebugLoc();
21253   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21254   MachineOperand MSrc = MI->getOperand(0);
21255   unsigned VSrc = MI->getOperand(5).getReg();
21256   const MachineOperand &Disp = MI->getOperand(3);
21257   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21258   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21259   if (hasDisp && MSrc.isReg())
21260     MSrc.setIsKill(false);
21261   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21262                                 .addOperand(/*Base=*/MSrc)
21263                                 .addImm(/*Scale=*/1)
21264                                 .addReg(/*Index=*/0)
21265                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21266                                 .addReg(0);
21267   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21268                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21269                           .addReg(VSrc)
21270                           .addOperand(/*Base=*/MSrc)
21271                           .addImm(/*Scale=*/1)
21272                           .addReg(/*Index=*/0)
21273                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21274                           .addReg(/*Segment=*/0);
21275   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21276   MI->eraseFromParent(); // The pseudo instruction is gone now.
21277   return BB;
21278 }
21279
21280 MachineBasicBlock *
21281 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21282                                         MachineBasicBlock *BB) const {
21283   MachineFunction *MF = BB->getParent();
21284   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21285   DebugLoc DL = MI->getDebugLoc();
21286   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21287
21288   assert(MF->shouldSplitStack());
21289
21290   const bool Is64Bit = Subtarget->is64Bit();
21291   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21292
21293   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21294   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21295
21296   // BB:
21297   //  ... [Till the alloca]
21298   // If stacklet is not large enough, jump to mallocMBB
21299   //
21300   // bumpMBB:
21301   //  Allocate by subtracting from RSP
21302   //  Jump to continueMBB
21303   //
21304   // mallocMBB:
21305   //  Allocate by call to runtime
21306   //
21307   // continueMBB:
21308   //  ...
21309   //  [rest of original BB]
21310   //
21311
21312   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21313   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21314   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21315
21316   MachineRegisterInfo &MRI = MF->getRegInfo();
21317   const TargetRegisterClass *AddrRegClass =
21318       getRegClassFor(getPointerTy(MF->getDataLayout()));
21319
21320   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21321     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21322     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21323     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21324     sizeVReg = MI->getOperand(1).getReg(),
21325     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21326
21327   MachineFunction::iterator MBBIter = ++BB->getIterator();
21328
21329   MF->insert(MBBIter, bumpMBB);
21330   MF->insert(MBBIter, mallocMBB);
21331   MF->insert(MBBIter, continueMBB);
21332
21333   continueMBB->splice(continueMBB->begin(), BB,
21334                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21335   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21336
21337   // Add code to the main basic block to check if the stack limit has been hit,
21338   // and if so, jump to mallocMBB otherwise to bumpMBB.
21339   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21340   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21341     .addReg(tmpSPVReg).addReg(sizeVReg);
21342   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21343     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21344     .addReg(SPLimitVReg);
21345   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21346
21347   // bumpMBB simply decreases the stack pointer, since we know the current
21348   // stacklet has enough space.
21349   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21350     .addReg(SPLimitVReg);
21351   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21352     .addReg(SPLimitVReg);
21353   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21354
21355   // Calls into a routine in libgcc to allocate more space from the heap.
21356   const uint32_t *RegMask =
21357       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21358   if (IsLP64) {
21359     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21360       .addReg(sizeVReg);
21361     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21362       .addExternalSymbol("__morestack_allocate_stack_space")
21363       .addRegMask(RegMask)
21364       .addReg(X86::RDI, RegState::Implicit)
21365       .addReg(X86::RAX, RegState::ImplicitDefine);
21366   } else if (Is64Bit) {
21367     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21368       .addReg(sizeVReg);
21369     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21370       .addExternalSymbol("__morestack_allocate_stack_space")
21371       .addRegMask(RegMask)
21372       .addReg(X86::EDI, RegState::Implicit)
21373       .addReg(X86::EAX, RegState::ImplicitDefine);
21374   } else {
21375     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21376       .addImm(12);
21377     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21378     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21379       .addExternalSymbol("__morestack_allocate_stack_space")
21380       .addRegMask(RegMask)
21381       .addReg(X86::EAX, RegState::ImplicitDefine);
21382   }
21383
21384   if (!Is64Bit)
21385     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21386       .addImm(16);
21387
21388   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21389     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21390   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21391
21392   // Set up the CFG correctly.
21393   BB->addSuccessor(bumpMBB);
21394   BB->addSuccessor(mallocMBB);
21395   mallocMBB->addSuccessor(continueMBB);
21396   bumpMBB->addSuccessor(continueMBB);
21397
21398   // Take care of the PHI nodes.
21399   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21400           MI->getOperand(0).getReg())
21401     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21402     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21403
21404   // Delete the original pseudo instruction.
21405   MI->eraseFromParent();
21406
21407   // And we're done.
21408   return continueMBB;
21409 }
21410
21411 MachineBasicBlock *
21412 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21413                                         MachineBasicBlock *BB) const {
21414   assert(!Subtarget->isTargetMachO());
21415   DebugLoc DL = MI->getDebugLoc();
21416   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21417       *BB->getParent(), *BB, MI, DL, false);
21418   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21419   MI->eraseFromParent(); // The pseudo instruction is gone now.
21420   return ResumeBB;
21421 }
21422
21423 MachineBasicBlock *
21424 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21425                                        MachineBasicBlock *BB) const {
21426   MachineFunction *MF = BB->getParent();
21427   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21428   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21429   DebugLoc DL = MI->getDebugLoc();
21430
21431   assert(!isAsynchronousEHPersonality(
21432              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
21433          "SEH does not use catchret!");
21434
21435   // Only 32-bit EH needs to worry about manually restoring stack pointers.
21436   if (!Subtarget->is32Bit())
21437     return BB;
21438
21439   // C++ EH creates a new target block to hold the restore code, and wires up
21440   // the new block to the return destination with a normal JMP_4.
21441   MachineBasicBlock *RestoreMBB =
21442       MF->CreateMachineBasicBlock(BB->getBasicBlock());
21443   assert(BB->succ_size() == 1);
21444   MF->insert(std::next(BB->getIterator()), RestoreMBB);
21445   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
21446   BB->addSuccessor(RestoreMBB);
21447   MI->getOperand(0).setMBB(RestoreMBB);
21448
21449   auto RestoreMBBI = RestoreMBB->begin();
21450   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
21451   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
21452   return BB;
21453 }
21454
21455 MachineBasicBlock *
21456 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
21457                                        MachineBasicBlock *BB) const {
21458   MachineFunction *MF = BB->getParent();
21459   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21460   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
21461   // Only 32-bit SEH requires special handling for catchpad.
21462   if (IsSEH && Subtarget->is32Bit()) {
21463     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21464     DebugLoc DL = MI->getDebugLoc();
21465     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
21466   }
21467   MI->eraseFromParent();
21468   return BB;
21469 }
21470
21471 MachineBasicBlock *
21472 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21473                                       MachineBasicBlock *BB) const {
21474   // This is pretty easy.  We're taking the value that we received from
21475   // our load from the relocation, sticking it in either RDI (x86-64)
21476   // or EAX and doing an indirect call.  The return value will then
21477   // be in the normal return register.
21478   MachineFunction *F = BB->getParent();
21479   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21480   DebugLoc DL = MI->getDebugLoc();
21481
21482   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21483   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21484
21485   // Get a register mask for the lowered call.
21486   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21487   // proper register mask.
21488   const uint32_t *RegMask =
21489       Subtarget->is64Bit() ?
21490       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
21491       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21492   if (Subtarget->is64Bit()) {
21493     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21494                                       TII->get(X86::MOV64rm), X86::RDI)
21495     .addReg(X86::RIP)
21496     .addImm(0).addReg(0)
21497     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21498                       MI->getOperand(3).getTargetFlags())
21499     .addReg(0);
21500     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21501     addDirectMem(MIB, X86::RDI);
21502     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21503   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21504     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21505                                       TII->get(X86::MOV32rm), X86::EAX)
21506     .addReg(0)
21507     .addImm(0).addReg(0)
21508     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21509                       MI->getOperand(3).getTargetFlags())
21510     .addReg(0);
21511     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21512     addDirectMem(MIB, X86::EAX);
21513     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21514   } else {
21515     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21516                                       TII->get(X86::MOV32rm), X86::EAX)
21517     .addReg(TII->getGlobalBaseReg(F))
21518     .addImm(0).addReg(0)
21519     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21520                       MI->getOperand(3).getTargetFlags())
21521     .addReg(0);
21522     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21523     addDirectMem(MIB, X86::EAX);
21524     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21525   }
21526
21527   MI->eraseFromParent(); // The pseudo instruction is gone now.
21528   return BB;
21529 }
21530
21531 MachineBasicBlock *
21532 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21533                                     MachineBasicBlock *MBB) const {
21534   DebugLoc DL = MI->getDebugLoc();
21535   MachineFunction *MF = MBB->getParent();
21536   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21537   MachineRegisterInfo &MRI = MF->getRegInfo();
21538
21539   const BasicBlock *BB = MBB->getBasicBlock();
21540   MachineFunction::iterator I = ++MBB->getIterator();
21541
21542   // Memory Reference
21543   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21544   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21545
21546   unsigned DstReg;
21547   unsigned MemOpndSlot = 0;
21548
21549   unsigned CurOp = 0;
21550
21551   DstReg = MI->getOperand(CurOp++).getReg();
21552   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21553   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21554   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21555   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21556
21557   MemOpndSlot = CurOp;
21558
21559   MVT PVT = getPointerTy(MF->getDataLayout());
21560   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21561          "Invalid Pointer Size!");
21562
21563   // For v = setjmp(buf), we generate
21564   //
21565   // thisMBB:
21566   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21567   //  SjLjSetup restoreMBB
21568   //
21569   // mainMBB:
21570   //  v_main = 0
21571   //
21572   // sinkMBB:
21573   //  v = phi(main, restore)
21574   //
21575   // restoreMBB:
21576   //  if base pointer being used, load it from frame
21577   //  v_restore = 1
21578
21579   MachineBasicBlock *thisMBB = MBB;
21580   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21581   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21582   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21583   MF->insert(I, mainMBB);
21584   MF->insert(I, sinkMBB);
21585   MF->push_back(restoreMBB);
21586   restoreMBB->setHasAddressTaken();
21587
21588   MachineInstrBuilder MIB;
21589
21590   // Transfer the remainder of BB and its successor edges to sinkMBB.
21591   sinkMBB->splice(sinkMBB->begin(), MBB,
21592                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21593   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21594
21595   // thisMBB:
21596   unsigned PtrStoreOpc = 0;
21597   unsigned LabelReg = 0;
21598   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21599   Reloc::Model RM = MF->getTarget().getRelocationModel();
21600   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21601                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21602
21603   // Prepare IP either in reg or imm.
21604   if (!UseImmLabel) {
21605     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21606     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21607     LabelReg = MRI.createVirtualRegister(PtrRC);
21608     if (Subtarget->is64Bit()) {
21609       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21610               .addReg(X86::RIP)
21611               .addImm(0)
21612               .addReg(0)
21613               .addMBB(restoreMBB)
21614               .addReg(0);
21615     } else {
21616       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21617       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21618               .addReg(XII->getGlobalBaseReg(MF))
21619               .addImm(0)
21620               .addReg(0)
21621               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21622               .addReg(0);
21623     }
21624   } else
21625     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21626   // Store IP
21627   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21628   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21629     if (i == X86::AddrDisp)
21630       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21631     else
21632       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21633   }
21634   if (!UseImmLabel)
21635     MIB.addReg(LabelReg);
21636   else
21637     MIB.addMBB(restoreMBB);
21638   MIB.setMemRefs(MMOBegin, MMOEnd);
21639   // Setup
21640   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21641           .addMBB(restoreMBB);
21642
21643   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21644   MIB.addRegMask(RegInfo->getNoPreservedMask());
21645   thisMBB->addSuccessor(mainMBB);
21646   thisMBB->addSuccessor(restoreMBB);
21647
21648   // mainMBB:
21649   //  EAX = 0
21650   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21651   mainMBB->addSuccessor(sinkMBB);
21652
21653   // sinkMBB:
21654   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21655           TII->get(X86::PHI), DstReg)
21656     .addReg(mainDstReg).addMBB(mainMBB)
21657     .addReg(restoreDstReg).addMBB(restoreMBB);
21658
21659   // restoreMBB:
21660   if (RegInfo->hasBasePointer(*MF)) {
21661     const bool Uses64BitFramePtr =
21662         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21663     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21664     X86FI->setRestoreBasePointer(MF);
21665     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21666     unsigned BasePtr = RegInfo->getBaseRegister();
21667     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21668     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21669                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21670       .setMIFlag(MachineInstr::FrameSetup);
21671   }
21672   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21673   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21674   restoreMBB->addSuccessor(sinkMBB);
21675
21676   MI->eraseFromParent();
21677   return sinkMBB;
21678 }
21679
21680 MachineBasicBlock *
21681 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21682                                      MachineBasicBlock *MBB) const {
21683   DebugLoc DL = MI->getDebugLoc();
21684   MachineFunction *MF = MBB->getParent();
21685   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21686   MachineRegisterInfo &MRI = MF->getRegInfo();
21687
21688   // Memory Reference
21689   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21690   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21691
21692   MVT PVT = getPointerTy(MF->getDataLayout());
21693   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21694          "Invalid Pointer Size!");
21695
21696   const TargetRegisterClass *RC =
21697     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21698   unsigned Tmp = MRI.createVirtualRegister(RC);
21699   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21700   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21701   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21702   unsigned SP = RegInfo->getStackRegister();
21703
21704   MachineInstrBuilder MIB;
21705
21706   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21707   const int64_t SPOffset = 2 * PVT.getStoreSize();
21708
21709   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21710   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21711
21712   // Reload FP
21713   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21714   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21715     MIB.addOperand(MI->getOperand(i));
21716   MIB.setMemRefs(MMOBegin, MMOEnd);
21717   // Reload IP
21718   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21719   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21720     if (i == X86::AddrDisp)
21721       MIB.addDisp(MI->getOperand(i), LabelOffset);
21722     else
21723       MIB.addOperand(MI->getOperand(i));
21724   }
21725   MIB.setMemRefs(MMOBegin, MMOEnd);
21726   // Reload SP
21727   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21728   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21729     if (i == X86::AddrDisp)
21730       MIB.addDisp(MI->getOperand(i), SPOffset);
21731     else
21732       MIB.addOperand(MI->getOperand(i));
21733   }
21734   MIB.setMemRefs(MMOBegin, MMOEnd);
21735   // Jump
21736   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21737
21738   MI->eraseFromParent();
21739   return MBB;
21740 }
21741
21742 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21743 // accumulator loops. Writing back to the accumulator allows the coalescer
21744 // to remove extra copies in the loop.
21745 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21746 MachineBasicBlock *
21747 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21748                                  MachineBasicBlock *MBB) const {
21749   MachineOperand &AddendOp = MI->getOperand(3);
21750
21751   // Bail out early if the addend isn't a register - we can't switch these.
21752   if (!AddendOp.isReg())
21753     return MBB;
21754
21755   MachineFunction &MF = *MBB->getParent();
21756   MachineRegisterInfo &MRI = MF.getRegInfo();
21757
21758   // Check whether the addend is defined by a PHI:
21759   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21760   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21761   if (!AddendDef.isPHI())
21762     return MBB;
21763
21764   // Look for the following pattern:
21765   // loop:
21766   //   %addend = phi [%entry, 0], [%loop, %result]
21767   //   ...
21768   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21769
21770   // Replace with:
21771   //   loop:
21772   //   %addend = phi [%entry, 0], [%loop, %result]
21773   //   ...
21774   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21775
21776   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21777     assert(AddendDef.getOperand(i).isReg());
21778     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21779     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21780     if (&PHISrcInst == MI) {
21781       // Found a matching instruction.
21782       unsigned NewFMAOpc = 0;
21783       switch (MI->getOpcode()) {
21784         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21785         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21786         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21787         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21788         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21789         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21790         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21791         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21792         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21793         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21794         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21795         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21796         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21797         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21798         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21799         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21800         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21801         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21802         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21803         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21804
21805         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21806         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21807         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21808         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21809         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21810         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21811         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21812         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21813         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21814         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21815         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21816         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21817         default: llvm_unreachable("Unrecognized FMA variant.");
21818       }
21819
21820       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21821       MachineInstrBuilder MIB =
21822         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21823         .addOperand(MI->getOperand(0))
21824         .addOperand(MI->getOperand(3))
21825         .addOperand(MI->getOperand(2))
21826         .addOperand(MI->getOperand(1));
21827       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21828       MI->eraseFromParent();
21829     }
21830   }
21831
21832   return MBB;
21833 }
21834
21835 MachineBasicBlock *
21836 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21837                                                MachineBasicBlock *BB) const {
21838   switch (MI->getOpcode()) {
21839   default: llvm_unreachable("Unexpected instr type to insert");
21840   case X86::TAILJMPd64:
21841   case X86::TAILJMPr64:
21842   case X86::TAILJMPm64:
21843   case X86::TAILJMPd64_REX:
21844   case X86::TAILJMPr64_REX:
21845   case X86::TAILJMPm64_REX:
21846     llvm_unreachable("TAILJMP64 would not be touched here.");
21847   case X86::TCRETURNdi64:
21848   case X86::TCRETURNri64:
21849   case X86::TCRETURNmi64:
21850     return BB;
21851   case X86::WIN_ALLOCA:
21852     return EmitLoweredWinAlloca(MI, BB);
21853   case X86::CATCHRET:
21854     return EmitLoweredCatchRet(MI, BB);
21855   case X86::CATCHPAD:
21856     return EmitLoweredCatchPad(MI, BB);
21857   case X86::SEG_ALLOCA_32:
21858   case X86::SEG_ALLOCA_64:
21859     return EmitLoweredSegAlloca(MI, BB);
21860   case X86::TLSCall_32:
21861   case X86::TLSCall_64:
21862     return EmitLoweredTLSCall(MI, BB);
21863   case X86::CMOV_FR32:
21864   case X86::CMOV_FR64:
21865   case X86::CMOV_GR8:
21866   case X86::CMOV_GR16:
21867   case X86::CMOV_GR32:
21868   case X86::CMOV_RFP32:
21869   case X86::CMOV_RFP64:
21870   case X86::CMOV_RFP80:
21871   case X86::CMOV_V2F64:
21872   case X86::CMOV_V2I64:
21873   case X86::CMOV_V4F32:
21874   case X86::CMOV_V4F64:
21875   case X86::CMOV_V4I64:
21876   case X86::CMOV_V16F32:
21877   case X86::CMOV_V8F32:
21878   case X86::CMOV_V8F64:
21879   case X86::CMOV_V8I64:
21880   case X86::CMOV_V8I1:
21881   case X86::CMOV_V16I1:
21882   case X86::CMOV_V32I1:
21883   case X86::CMOV_V64I1:
21884     return EmitLoweredSelect(MI, BB);
21885
21886   case X86::RELEASE_FADD32mr:
21887   case X86::RELEASE_FADD64mr:
21888     return EmitLoweredAtomicFP(MI, BB);
21889
21890   case X86::FP32_TO_INT16_IN_MEM:
21891   case X86::FP32_TO_INT32_IN_MEM:
21892   case X86::FP32_TO_INT64_IN_MEM:
21893   case X86::FP64_TO_INT16_IN_MEM:
21894   case X86::FP64_TO_INT32_IN_MEM:
21895   case X86::FP64_TO_INT64_IN_MEM:
21896   case X86::FP80_TO_INT16_IN_MEM:
21897   case X86::FP80_TO_INT32_IN_MEM:
21898   case X86::FP80_TO_INT64_IN_MEM: {
21899     MachineFunction *F = BB->getParent();
21900     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21901     DebugLoc DL = MI->getDebugLoc();
21902
21903     // Change the floating point control register to use "round towards zero"
21904     // mode when truncating to an integer value.
21905     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21906     addFrameReference(BuildMI(*BB, MI, DL,
21907                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21908
21909     // Load the old value of the high byte of the control word...
21910     unsigned OldCW =
21911       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21912     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21913                       CWFrameIdx);
21914
21915     // Set the high part to be round to zero...
21916     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21917       .addImm(0xC7F);
21918
21919     // Reload the modified control word now...
21920     addFrameReference(BuildMI(*BB, MI, DL,
21921                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21922
21923     // Restore the memory image of control word to original value
21924     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21925       .addReg(OldCW);
21926
21927     // Get the X86 opcode to use.
21928     unsigned Opc;
21929     switch (MI->getOpcode()) {
21930     default: llvm_unreachable("illegal opcode!");
21931     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21932     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21933     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21934     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21935     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21936     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21937     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21938     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21939     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21940     }
21941
21942     X86AddressMode AM;
21943     MachineOperand &Op = MI->getOperand(0);
21944     if (Op.isReg()) {
21945       AM.BaseType = X86AddressMode::RegBase;
21946       AM.Base.Reg = Op.getReg();
21947     } else {
21948       AM.BaseType = X86AddressMode::FrameIndexBase;
21949       AM.Base.FrameIndex = Op.getIndex();
21950     }
21951     Op = MI->getOperand(1);
21952     if (Op.isImm())
21953       AM.Scale = Op.getImm();
21954     Op = MI->getOperand(2);
21955     if (Op.isImm())
21956       AM.IndexReg = Op.getImm();
21957     Op = MI->getOperand(3);
21958     if (Op.isGlobal()) {
21959       AM.GV = Op.getGlobal();
21960     } else {
21961       AM.Disp = Op.getImm();
21962     }
21963     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21964                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21965
21966     // Reload the original control word now.
21967     addFrameReference(BuildMI(*BB, MI, DL,
21968                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21969
21970     MI->eraseFromParent();   // The pseudo instruction is gone now.
21971     return BB;
21972   }
21973     // String/text processing lowering.
21974   case X86::PCMPISTRM128REG:
21975   case X86::VPCMPISTRM128REG:
21976   case X86::PCMPISTRM128MEM:
21977   case X86::VPCMPISTRM128MEM:
21978   case X86::PCMPESTRM128REG:
21979   case X86::VPCMPESTRM128REG:
21980   case X86::PCMPESTRM128MEM:
21981   case X86::VPCMPESTRM128MEM:
21982     assert(Subtarget->hasSSE42() &&
21983            "Target must have SSE4.2 or AVX features enabled");
21984     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21985
21986   // String/text processing lowering.
21987   case X86::PCMPISTRIREG:
21988   case X86::VPCMPISTRIREG:
21989   case X86::PCMPISTRIMEM:
21990   case X86::VPCMPISTRIMEM:
21991   case X86::PCMPESTRIREG:
21992   case X86::VPCMPESTRIREG:
21993   case X86::PCMPESTRIMEM:
21994   case X86::VPCMPESTRIMEM:
21995     assert(Subtarget->hasSSE42() &&
21996            "Target must have SSE4.2 or AVX features enabled");
21997     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21998
21999   // Thread synchronization.
22000   case X86::MONITOR:
22001     return EmitMonitor(MI, BB, Subtarget);
22002
22003   // xbegin
22004   case X86::XBEGIN:
22005     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22006
22007   case X86::VASTART_SAVE_XMM_REGS:
22008     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22009
22010   case X86::VAARG_64:
22011     return EmitVAARG64WithCustomInserter(MI, BB);
22012
22013   case X86::EH_SjLj_SetJmp32:
22014   case X86::EH_SjLj_SetJmp64:
22015     return emitEHSjLjSetJmp(MI, BB);
22016
22017   case X86::EH_SjLj_LongJmp32:
22018   case X86::EH_SjLj_LongJmp64:
22019     return emitEHSjLjLongJmp(MI, BB);
22020
22021   case TargetOpcode::STATEPOINT:
22022     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22023     // this point in the process.  We diverge later.
22024     return emitPatchPoint(MI, BB);
22025
22026   case TargetOpcode::STACKMAP:
22027   case TargetOpcode::PATCHPOINT:
22028     return emitPatchPoint(MI, BB);
22029
22030   case X86::VFMADDPDr213r:
22031   case X86::VFMADDPSr213r:
22032   case X86::VFMADDSDr213r:
22033   case X86::VFMADDSSr213r:
22034   case X86::VFMSUBPDr213r:
22035   case X86::VFMSUBPSr213r:
22036   case X86::VFMSUBSDr213r:
22037   case X86::VFMSUBSSr213r:
22038   case X86::VFNMADDPDr213r:
22039   case X86::VFNMADDPSr213r:
22040   case X86::VFNMADDSDr213r:
22041   case X86::VFNMADDSSr213r:
22042   case X86::VFNMSUBPDr213r:
22043   case X86::VFNMSUBPSr213r:
22044   case X86::VFNMSUBSDr213r:
22045   case X86::VFNMSUBSSr213r:
22046   case X86::VFMADDSUBPDr213r:
22047   case X86::VFMADDSUBPSr213r:
22048   case X86::VFMSUBADDPDr213r:
22049   case X86::VFMSUBADDPSr213r:
22050   case X86::VFMADDPDr213rY:
22051   case X86::VFMADDPSr213rY:
22052   case X86::VFMSUBPDr213rY:
22053   case X86::VFMSUBPSr213rY:
22054   case X86::VFNMADDPDr213rY:
22055   case X86::VFNMADDPSr213rY:
22056   case X86::VFNMSUBPDr213rY:
22057   case X86::VFNMSUBPSr213rY:
22058   case X86::VFMADDSUBPDr213rY:
22059   case X86::VFMADDSUBPSr213rY:
22060   case X86::VFMSUBADDPDr213rY:
22061   case X86::VFMSUBADDPSr213rY:
22062     return emitFMA3Instr(MI, BB);
22063   }
22064 }
22065
22066 //===----------------------------------------------------------------------===//
22067 //                           X86 Optimization Hooks
22068 //===----------------------------------------------------------------------===//
22069
22070 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22071                                                       APInt &KnownZero,
22072                                                       APInt &KnownOne,
22073                                                       const SelectionDAG &DAG,
22074                                                       unsigned Depth) const {
22075   unsigned BitWidth = KnownZero.getBitWidth();
22076   unsigned Opc = Op.getOpcode();
22077   assert((Opc >= ISD::BUILTIN_OP_END ||
22078           Opc == ISD::INTRINSIC_WO_CHAIN ||
22079           Opc == ISD::INTRINSIC_W_CHAIN ||
22080           Opc == ISD::INTRINSIC_VOID) &&
22081          "Should use MaskedValueIsZero if you don't know whether Op"
22082          " is a target node!");
22083
22084   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22085   switch (Opc) {
22086   default: break;
22087   case X86ISD::ADD:
22088   case X86ISD::SUB:
22089   case X86ISD::ADC:
22090   case X86ISD::SBB:
22091   case X86ISD::SMUL:
22092   case X86ISD::UMUL:
22093   case X86ISD::INC:
22094   case X86ISD::DEC:
22095   case X86ISD::OR:
22096   case X86ISD::XOR:
22097   case X86ISD::AND:
22098     // These nodes' second result is a boolean.
22099     if (Op.getResNo() == 0)
22100       break;
22101     // Fallthrough
22102   case X86ISD::SETCC:
22103     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22104     break;
22105   case ISD::INTRINSIC_WO_CHAIN: {
22106     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22107     unsigned NumLoBits = 0;
22108     switch (IntId) {
22109     default: break;
22110     case Intrinsic::x86_sse_movmsk_ps:
22111     case Intrinsic::x86_avx_movmsk_ps_256:
22112     case Intrinsic::x86_sse2_movmsk_pd:
22113     case Intrinsic::x86_avx_movmsk_pd_256:
22114     case Intrinsic::x86_mmx_pmovmskb:
22115     case Intrinsic::x86_sse2_pmovmskb_128:
22116     case Intrinsic::x86_avx2_pmovmskb: {
22117       // High bits of movmskp{s|d}, pmovmskb are known zero.
22118       switch (IntId) {
22119         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22120         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22121         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22122         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22123         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22124         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22125         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22126         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22127       }
22128       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22129       break;
22130     }
22131     }
22132     break;
22133   }
22134   }
22135 }
22136
22137 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22138   SDValue Op,
22139   const SelectionDAG &,
22140   unsigned Depth) const {
22141   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22142   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22143     return Op.getValueType().getScalarSizeInBits();
22144
22145   // Fallback case.
22146   return 1;
22147 }
22148
22149 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22150 /// node is a GlobalAddress + offset.
22151 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22152                                        const GlobalValue* &GA,
22153                                        int64_t &Offset) const {
22154   if (N->getOpcode() == X86ISD::Wrapper) {
22155     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22156       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22157       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22158       return true;
22159     }
22160   }
22161   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22162 }
22163
22164 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22165 /// same as extracting the high 128-bit part of 256-bit vector and then
22166 /// inserting the result into the low part of a new 256-bit vector
22167 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22168   EVT VT = SVOp->getValueType(0);
22169   unsigned NumElems = VT.getVectorNumElements();
22170
22171   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22172   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22173     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22174         SVOp->getMaskElt(j) >= 0)
22175       return false;
22176
22177   return true;
22178 }
22179
22180 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22181 /// same as extracting the low 128-bit part of 256-bit vector and then
22182 /// inserting the result into the high part of a new 256-bit vector
22183 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22184   EVT VT = SVOp->getValueType(0);
22185   unsigned NumElems = VT.getVectorNumElements();
22186
22187   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22188   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22189     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22190         SVOp->getMaskElt(j) >= 0)
22191       return false;
22192
22193   return true;
22194 }
22195
22196 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22197 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22198                                         TargetLowering::DAGCombinerInfo &DCI,
22199                                         const X86Subtarget* Subtarget) {
22200   SDLoc dl(N);
22201   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22202   SDValue V1 = SVOp->getOperand(0);
22203   SDValue V2 = SVOp->getOperand(1);
22204   EVT VT = SVOp->getValueType(0);
22205   unsigned NumElems = VT.getVectorNumElements();
22206
22207   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22208       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22209     //
22210     //                   0,0,0,...
22211     //                      |
22212     //    V      UNDEF    BUILD_VECTOR    UNDEF
22213     //     \      /           \           /
22214     //  CONCAT_VECTOR         CONCAT_VECTOR
22215     //         \                  /
22216     //          \                /
22217     //          RESULT: V + zero extended
22218     //
22219     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22220         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22221         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22222       return SDValue();
22223
22224     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22225       return SDValue();
22226
22227     // To match the shuffle mask, the first half of the mask should
22228     // be exactly the first vector, and all the rest a splat with the
22229     // first element of the second one.
22230     for (unsigned i = 0; i != NumElems/2; ++i)
22231       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22232           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22233         return SDValue();
22234
22235     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22236     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22237       if (Ld->hasNUsesOfValue(1, 0)) {
22238         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22239         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22240         SDValue ResNode =
22241           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22242                                   Ld->getMemoryVT(),
22243                                   Ld->getPointerInfo(),
22244                                   Ld->getAlignment(),
22245                                   false/*isVolatile*/, true/*ReadMem*/,
22246                                   false/*WriteMem*/);
22247
22248         // Make sure the newly-created LOAD is in the same position as Ld in
22249         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22250         // and update uses of Ld's output chain to use the TokenFactor.
22251         if (Ld->hasAnyUseOfValue(1)) {
22252           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22253                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22254           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22255           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22256                                  SDValue(ResNode.getNode(), 1));
22257         }
22258
22259         return DAG.getBitcast(VT, ResNode);
22260       }
22261     }
22262
22263     // Emit a zeroed vector and insert the desired subvector on its
22264     // first half.
22265     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22266     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22267     return DCI.CombineTo(N, InsV);
22268   }
22269
22270   //===--------------------------------------------------------------------===//
22271   // Combine some shuffles into subvector extracts and inserts:
22272   //
22273
22274   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22275   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22276     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22277     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22278     return DCI.CombineTo(N, InsV);
22279   }
22280
22281   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22282   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22283     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22284     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22285     return DCI.CombineTo(N, InsV);
22286   }
22287
22288   return SDValue();
22289 }
22290
22291 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22292 /// possible.
22293 ///
22294 /// This is the leaf of the recursive combinine below. When we have found some
22295 /// chain of single-use x86 shuffle instructions and accumulated the combined
22296 /// shuffle mask represented by them, this will try to pattern match that mask
22297 /// into either a single instruction if there is a special purpose instruction
22298 /// for this operation, or into a PSHUFB instruction which is a fully general
22299 /// instruction but should only be used to replace chains over a certain depth.
22300 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22301                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22302                                    TargetLowering::DAGCombinerInfo &DCI,
22303                                    const X86Subtarget *Subtarget) {
22304   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22305
22306   // Find the operand that enters the chain. Note that multiple uses are OK
22307   // here, we're not going to remove the operand we find.
22308   SDValue Input = Op.getOperand(0);
22309   while (Input.getOpcode() == ISD::BITCAST)
22310     Input = Input.getOperand(0);
22311
22312   MVT VT = Input.getSimpleValueType();
22313   MVT RootVT = Root.getSimpleValueType();
22314   SDLoc DL(Root);
22315
22316   if (Mask.size() == 1) {
22317     int Index = Mask[0];
22318     assert((Index >= 0 || Index == SM_SentinelUndef ||
22319             Index == SM_SentinelZero) &&
22320            "Invalid shuffle index found!");
22321
22322     // We may end up with an accumulated mask of size 1 as a result of
22323     // widening of shuffle operands (see function canWidenShuffleElements).
22324     // If the only shuffle index is equal to SM_SentinelZero then propagate
22325     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22326     // mask, and therefore the entire chain of shuffles can be folded away.
22327     if (Index == SM_SentinelZero)
22328       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22329     else
22330       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22331                     /*AddTo*/ true);
22332     return true;
22333   }
22334
22335   // Use the float domain if the operand type is a floating point type.
22336   bool FloatDomain = VT.isFloatingPoint();
22337
22338   // For floating point shuffles, we don't have free copies in the shuffle
22339   // instructions or the ability to load as part of the instruction, so
22340   // canonicalize their shuffles to UNPCK or MOV variants.
22341   //
22342   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22343   // vectors because it can have a load folded into it that UNPCK cannot. This
22344   // doesn't preclude something switching to the shorter encoding post-RA.
22345   //
22346   // FIXME: Should teach these routines about AVX vector widths.
22347   if (FloatDomain && VT.is128BitVector()) {
22348     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22349       bool Lo = Mask.equals({0, 0});
22350       unsigned Shuffle;
22351       MVT ShuffleVT;
22352       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22353       // is no slower than UNPCKLPD but has the option to fold the input operand
22354       // into even an unaligned memory load.
22355       if (Lo && Subtarget->hasSSE3()) {
22356         Shuffle = X86ISD::MOVDDUP;
22357         ShuffleVT = MVT::v2f64;
22358       } else {
22359         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22360         // than the UNPCK variants.
22361         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22362         ShuffleVT = MVT::v4f32;
22363       }
22364       if (Depth == 1 && Root->getOpcode() == Shuffle)
22365         return false; // Nothing to do!
22366       Op = DAG.getBitcast(ShuffleVT, Input);
22367       DCI.AddToWorklist(Op.getNode());
22368       if (Shuffle == X86ISD::MOVDDUP)
22369         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22370       else
22371         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22372       DCI.AddToWorklist(Op.getNode());
22373       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22374                     /*AddTo*/ true);
22375       return true;
22376     }
22377     if (Subtarget->hasSSE3() &&
22378         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22379       bool Lo = Mask.equals({0, 0, 2, 2});
22380       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22381       MVT ShuffleVT = MVT::v4f32;
22382       if (Depth == 1 && Root->getOpcode() == Shuffle)
22383         return false; // Nothing to do!
22384       Op = DAG.getBitcast(ShuffleVT, Input);
22385       DCI.AddToWorklist(Op.getNode());
22386       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22387       DCI.AddToWorklist(Op.getNode());
22388       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22389                     /*AddTo*/ true);
22390       return true;
22391     }
22392     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22393       bool Lo = Mask.equals({0, 0, 1, 1});
22394       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22395       MVT ShuffleVT = MVT::v4f32;
22396       if (Depth == 1 && Root->getOpcode() == Shuffle)
22397         return false; // Nothing to do!
22398       Op = DAG.getBitcast(ShuffleVT, Input);
22399       DCI.AddToWorklist(Op.getNode());
22400       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22401       DCI.AddToWorklist(Op.getNode());
22402       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22403                     /*AddTo*/ true);
22404       return true;
22405     }
22406   }
22407
22408   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22409   // variants as none of these have single-instruction variants that are
22410   // superior to the UNPCK formulation.
22411   if (!FloatDomain && VT.is128BitVector() &&
22412       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22413        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22414        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22415        Mask.equals(
22416            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22417     bool Lo = Mask[0] == 0;
22418     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22419     if (Depth == 1 && Root->getOpcode() == Shuffle)
22420       return false; // Nothing to do!
22421     MVT ShuffleVT;
22422     switch (Mask.size()) {
22423     case 8:
22424       ShuffleVT = MVT::v8i16;
22425       break;
22426     case 16:
22427       ShuffleVT = MVT::v16i8;
22428       break;
22429     default:
22430       llvm_unreachable("Impossible mask size!");
22431     };
22432     Op = DAG.getBitcast(ShuffleVT, Input);
22433     DCI.AddToWorklist(Op.getNode());
22434     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22435     DCI.AddToWorklist(Op.getNode());
22436     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22437                   /*AddTo*/ true);
22438     return true;
22439   }
22440
22441   // Don't try to re-form single instruction chains under any circumstances now
22442   // that we've done encoding canonicalization for them.
22443   if (Depth < 2)
22444     return false;
22445
22446   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22447   // can replace them with a single PSHUFB instruction profitably. Intel's
22448   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22449   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22450   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22451     SmallVector<SDValue, 16> PSHUFBMask;
22452     int NumBytes = VT.getSizeInBits() / 8;
22453     int Ratio = NumBytes / Mask.size();
22454     for (int i = 0; i < NumBytes; ++i) {
22455       if (Mask[i / Ratio] == SM_SentinelUndef) {
22456         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22457         continue;
22458       }
22459       int M = Mask[i / Ratio] != SM_SentinelZero
22460                   ? Ratio * Mask[i / Ratio] + i % Ratio
22461                   : 255;
22462       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22463     }
22464     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22465     Op = DAG.getBitcast(ByteVT, Input);
22466     DCI.AddToWorklist(Op.getNode());
22467     SDValue PSHUFBMaskOp =
22468         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22469     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22470     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22471     DCI.AddToWorklist(Op.getNode());
22472     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22473                   /*AddTo*/ true);
22474     return true;
22475   }
22476
22477   // Failed to find any combines.
22478   return false;
22479 }
22480
22481 /// \brief Fully generic combining of x86 shuffle instructions.
22482 ///
22483 /// This should be the last combine run over the x86 shuffle instructions. Once
22484 /// they have been fully optimized, this will recursively consider all chains
22485 /// of single-use shuffle instructions, build a generic model of the cumulative
22486 /// shuffle operation, and check for simpler instructions which implement this
22487 /// operation. We use this primarily for two purposes:
22488 ///
22489 /// 1) Collapse generic shuffles to specialized single instructions when
22490 ///    equivalent. In most cases, this is just an encoding size win, but
22491 ///    sometimes we will collapse multiple generic shuffles into a single
22492 ///    special-purpose shuffle.
22493 /// 2) Look for sequences of shuffle instructions with 3 or more total
22494 ///    instructions, and replace them with the slightly more expensive SSSE3
22495 ///    PSHUFB instruction if available. We do this as the last combining step
22496 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22497 ///    a suitable short sequence of other instructions. The PHUFB will either
22498 ///    use a register or have to read from memory and so is slightly (but only
22499 ///    slightly) more expensive than the other shuffle instructions.
22500 ///
22501 /// Because this is inherently a quadratic operation (for each shuffle in
22502 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22503 /// This should never be an issue in practice as the shuffle lowering doesn't
22504 /// produce sequences of more than 8 instructions.
22505 ///
22506 /// FIXME: We will currently miss some cases where the redundant shuffling
22507 /// would simplify under the threshold for PSHUFB formation because of
22508 /// combine-ordering. To fix this, we should do the redundant instruction
22509 /// combining in this recursive walk.
22510 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22511                                           ArrayRef<int> RootMask,
22512                                           int Depth, bool HasPSHUFB,
22513                                           SelectionDAG &DAG,
22514                                           TargetLowering::DAGCombinerInfo &DCI,
22515                                           const X86Subtarget *Subtarget) {
22516   // Bound the depth of our recursive combine because this is ultimately
22517   // quadratic in nature.
22518   if (Depth > 8)
22519     return false;
22520
22521   // Directly rip through bitcasts to find the underlying operand.
22522   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22523     Op = Op.getOperand(0);
22524
22525   MVT VT = Op.getSimpleValueType();
22526   if (!VT.isVector())
22527     return false; // Bail if we hit a non-vector.
22528
22529   assert(Root.getSimpleValueType().isVector() &&
22530          "Shuffles operate on vector types!");
22531   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22532          "Can only combine shuffles of the same vector register size.");
22533
22534   if (!isTargetShuffle(Op.getOpcode()))
22535     return false;
22536   SmallVector<int, 16> OpMask;
22537   bool IsUnary;
22538   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22539   // We only can combine unary shuffles which we can decode the mask for.
22540   if (!HaveMask || !IsUnary)
22541     return false;
22542
22543   assert(VT.getVectorNumElements() == OpMask.size() &&
22544          "Different mask size from vector size!");
22545   assert(((RootMask.size() > OpMask.size() &&
22546            RootMask.size() % OpMask.size() == 0) ||
22547           (OpMask.size() > RootMask.size() &&
22548            OpMask.size() % RootMask.size() == 0) ||
22549           OpMask.size() == RootMask.size()) &&
22550          "The smaller number of elements must divide the larger.");
22551   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22552   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22553   assert(((RootRatio == 1 && OpRatio == 1) ||
22554           (RootRatio == 1) != (OpRatio == 1)) &&
22555          "Must not have a ratio for both incoming and op masks!");
22556
22557   SmallVector<int, 16> Mask;
22558   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22559
22560   // Merge this shuffle operation's mask into our accumulated mask. Note that
22561   // this shuffle's mask will be the first applied to the input, followed by the
22562   // root mask to get us all the way to the root value arrangement. The reason
22563   // for this order is that we are recursing up the operation chain.
22564   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22565     int RootIdx = i / RootRatio;
22566     if (RootMask[RootIdx] < 0) {
22567       // This is a zero or undef lane, we're done.
22568       Mask.push_back(RootMask[RootIdx]);
22569       continue;
22570     }
22571
22572     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22573     int OpIdx = RootMaskedIdx / OpRatio;
22574     if (OpMask[OpIdx] < 0) {
22575       // The incoming lanes are zero or undef, it doesn't matter which ones we
22576       // are using.
22577       Mask.push_back(OpMask[OpIdx]);
22578       continue;
22579     }
22580
22581     // Ok, we have non-zero lanes, map them through.
22582     Mask.push_back(OpMask[OpIdx] * OpRatio +
22583                    RootMaskedIdx % OpRatio);
22584   }
22585
22586   // See if we can recurse into the operand to combine more things.
22587   switch (Op.getOpcode()) {
22588   case X86ISD::PSHUFB:
22589     HasPSHUFB = true;
22590   case X86ISD::PSHUFD:
22591   case X86ISD::PSHUFHW:
22592   case X86ISD::PSHUFLW:
22593     if (Op.getOperand(0).hasOneUse() &&
22594         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22595                                       HasPSHUFB, DAG, DCI, Subtarget))
22596       return true;
22597     break;
22598
22599   case X86ISD::UNPCKL:
22600   case X86ISD::UNPCKH:
22601     assert(Op.getOperand(0) == Op.getOperand(1) &&
22602            "We only combine unary shuffles!");
22603     // We can't check for single use, we have to check that this shuffle is the
22604     // only user.
22605     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22606         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22607                                       HasPSHUFB, DAG, DCI, Subtarget))
22608       return true;
22609     break;
22610   }
22611
22612   // Minor canonicalization of the accumulated shuffle mask to make it easier
22613   // to match below. All this does is detect masks with squential pairs of
22614   // elements, and shrink them to the half-width mask. It does this in a loop
22615   // so it will reduce the size of the mask to the minimal width mask which
22616   // performs an equivalent shuffle.
22617   SmallVector<int, 16> WidenedMask;
22618   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22619     Mask = std::move(WidenedMask);
22620     WidenedMask.clear();
22621   }
22622
22623   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22624                                 Subtarget);
22625 }
22626
22627 /// \brief Get the PSHUF-style mask from PSHUF node.
22628 ///
22629 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22630 /// PSHUF-style masks that can be reused with such instructions.
22631 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22632   MVT VT = N.getSimpleValueType();
22633   SmallVector<int, 4> Mask;
22634   bool IsUnary;
22635   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22636   (void)HaveMask;
22637   assert(HaveMask);
22638
22639   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22640   // matter. Check that the upper masks are repeats and remove them.
22641   if (VT.getSizeInBits() > 128) {
22642     int LaneElts = 128 / VT.getScalarSizeInBits();
22643 #ifndef NDEBUG
22644     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22645       for (int j = 0; j < LaneElts; ++j)
22646         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22647                "Mask doesn't repeat in high 128-bit lanes!");
22648 #endif
22649     Mask.resize(LaneElts);
22650   }
22651
22652   switch (N.getOpcode()) {
22653   case X86ISD::PSHUFD:
22654     return Mask;
22655   case X86ISD::PSHUFLW:
22656     Mask.resize(4);
22657     return Mask;
22658   case X86ISD::PSHUFHW:
22659     Mask.erase(Mask.begin(), Mask.begin() + 4);
22660     for (int &M : Mask)
22661       M -= 4;
22662     return Mask;
22663   default:
22664     llvm_unreachable("No valid shuffle instruction found!");
22665   }
22666 }
22667
22668 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22669 ///
22670 /// We walk up the chain and look for a combinable shuffle, skipping over
22671 /// shuffles that we could hoist this shuffle's transformation past without
22672 /// altering anything.
22673 static SDValue
22674 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22675                              SelectionDAG &DAG,
22676                              TargetLowering::DAGCombinerInfo &DCI) {
22677   assert(N.getOpcode() == X86ISD::PSHUFD &&
22678          "Called with something other than an x86 128-bit half shuffle!");
22679   SDLoc DL(N);
22680
22681   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22682   // of the shuffles in the chain so that we can form a fresh chain to replace
22683   // this one.
22684   SmallVector<SDValue, 8> Chain;
22685   SDValue V = N.getOperand(0);
22686   for (; V.hasOneUse(); V = V.getOperand(0)) {
22687     switch (V.getOpcode()) {
22688     default:
22689       return SDValue(); // Nothing combined!
22690
22691     case ISD::BITCAST:
22692       // Skip bitcasts as we always know the type for the target specific
22693       // instructions.
22694       continue;
22695
22696     case X86ISD::PSHUFD:
22697       // Found another dword shuffle.
22698       break;
22699
22700     case X86ISD::PSHUFLW:
22701       // Check that the low words (being shuffled) are the identity in the
22702       // dword shuffle, and the high words are self-contained.
22703       if (Mask[0] != 0 || Mask[1] != 1 ||
22704           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22705         return SDValue();
22706
22707       Chain.push_back(V);
22708       continue;
22709
22710     case X86ISD::PSHUFHW:
22711       // Check that the high words (being shuffled) are the identity in the
22712       // dword shuffle, and the low words are self-contained.
22713       if (Mask[2] != 2 || Mask[3] != 3 ||
22714           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22715         return SDValue();
22716
22717       Chain.push_back(V);
22718       continue;
22719
22720     case X86ISD::UNPCKL:
22721     case X86ISD::UNPCKH:
22722       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22723       // shuffle into a preceding word shuffle.
22724       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
22725           V.getSimpleValueType().getVectorElementType() != MVT::i16)
22726         return SDValue();
22727
22728       // Search for a half-shuffle which we can combine with.
22729       unsigned CombineOp =
22730           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22731       if (V.getOperand(0) != V.getOperand(1) ||
22732           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22733         return SDValue();
22734       Chain.push_back(V);
22735       V = V.getOperand(0);
22736       do {
22737         switch (V.getOpcode()) {
22738         default:
22739           return SDValue(); // Nothing to combine.
22740
22741         case X86ISD::PSHUFLW:
22742         case X86ISD::PSHUFHW:
22743           if (V.getOpcode() == CombineOp)
22744             break;
22745
22746           Chain.push_back(V);
22747
22748           // Fallthrough!
22749         case ISD::BITCAST:
22750           V = V.getOperand(0);
22751           continue;
22752         }
22753         break;
22754       } while (V.hasOneUse());
22755       break;
22756     }
22757     // Break out of the loop if we break out of the switch.
22758     break;
22759   }
22760
22761   if (!V.hasOneUse())
22762     // We fell out of the loop without finding a viable combining instruction.
22763     return SDValue();
22764
22765   // Merge this node's mask and our incoming mask.
22766   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22767   for (int &M : Mask)
22768     M = VMask[M];
22769   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22770                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22771
22772   // Rebuild the chain around this new shuffle.
22773   while (!Chain.empty()) {
22774     SDValue W = Chain.pop_back_val();
22775
22776     if (V.getValueType() != W.getOperand(0).getValueType())
22777       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22778
22779     switch (W.getOpcode()) {
22780     default:
22781       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22782
22783     case X86ISD::UNPCKL:
22784     case X86ISD::UNPCKH:
22785       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22786       break;
22787
22788     case X86ISD::PSHUFD:
22789     case X86ISD::PSHUFLW:
22790     case X86ISD::PSHUFHW:
22791       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22792       break;
22793     }
22794   }
22795   if (V.getValueType() != N.getValueType())
22796     V = DAG.getBitcast(N.getValueType(), V);
22797
22798   // Return the new chain to replace N.
22799   return V;
22800 }
22801
22802 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22803 /// pshufhw.
22804 ///
22805 /// We walk up the chain, skipping shuffles of the other half and looking
22806 /// through shuffles which switch halves trying to find a shuffle of the same
22807 /// pair of dwords.
22808 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22809                                         SelectionDAG &DAG,
22810                                         TargetLowering::DAGCombinerInfo &DCI) {
22811   assert(
22812       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22813       "Called with something other than an x86 128-bit half shuffle!");
22814   SDLoc DL(N);
22815   unsigned CombineOpcode = N.getOpcode();
22816
22817   // Walk up a single-use chain looking for a combinable shuffle.
22818   SDValue V = N.getOperand(0);
22819   for (; V.hasOneUse(); V = V.getOperand(0)) {
22820     switch (V.getOpcode()) {
22821     default:
22822       return false; // Nothing combined!
22823
22824     case ISD::BITCAST:
22825       // Skip bitcasts as we always know the type for the target specific
22826       // instructions.
22827       continue;
22828
22829     case X86ISD::PSHUFLW:
22830     case X86ISD::PSHUFHW:
22831       if (V.getOpcode() == CombineOpcode)
22832         break;
22833
22834       // Other-half shuffles are no-ops.
22835       continue;
22836     }
22837     // Break out of the loop if we break out of the switch.
22838     break;
22839   }
22840
22841   if (!V.hasOneUse())
22842     // We fell out of the loop without finding a viable combining instruction.
22843     return false;
22844
22845   // Combine away the bottom node as its shuffle will be accumulated into
22846   // a preceding shuffle.
22847   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22848
22849   // Record the old value.
22850   SDValue Old = V;
22851
22852   // Merge this node's mask and our incoming mask (adjusted to account for all
22853   // the pshufd instructions encountered).
22854   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22855   for (int &M : Mask)
22856     M = VMask[M];
22857   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22858                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22859
22860   // Check that the shuffles didn't cancel each other out. If not, we need to
22861   // combine to the new one.
22862   if (Old != V)
22863     // Replace the combinable shuffle with the combined one, updating all users
22864     // so that we re-evaluate the chain here.
22865     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22866
22867   return true;
22868 }
22869
22870 /// \brief Try to combine x86 target specific shuffles.
22871 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22872                                            TargetLowering::DAGCombinerInfo &DCI,
22873                                            const X86Subtarget *Subtarget) {
22874   SDLoc DL(N);
22875   MVT VT = N.getSimpleValueType();
22876   SmallVector<int, 4> Mask;
22877
22878   switch (N.getOpcode()) {
22879   case X86ISD::PSHUFD:
22880   case X86ISD::PSHUFLW:
22881   case X86ISD::PSHUFHW:
22882     Mask = getPSHUFShuffleMask(N);
22883     assert(Mask.size() == 4);
22884     break;
22885   case X86ISD::UNPCKL: {
22886     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
22887     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
22888     // moves upper half elements into the lower half part. For example:
22889     //
22890     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
22891     //     undef:v16i8
22892     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
22893     //
22894     // will be combined to:
22895     //
22896     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
22897
22898     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
22899     // happen due to advanced instructions.
22900     if (!VT.is128BitVector())
22901       return SDValue();
22902
22903     auto Op0 = N.getOperand(0);
22904     auto Op1 = N.getOperand(1);
22905     if (Op0.getOpcode() == ISD::UNDEF &&
22906         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
22907       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
22908
22909       unsigned NumElts = VT.getVectorNumElements();
22910       SmallVector<int, 8> ExpectedMask(NumElts, -1);
22911       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
22912                 NumElts / 2);
22913
22914       auto ShufOp = Op1.getOperand(0);
22915       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
22916         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
22917     }
22918     return SDValue();
22919   }
22920   default:
22921     return SDValue();
22922   }
22923
22924   // Nuke no-op shuffles that show up after combining.
22925   if (isNoopShuffleMask(Mask))
22926     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22927
22928   // Look for simplifications involving one or two shuffle instructions.
22929   SDValue V = N.getOperand(0);
22930   switch (N.getOpcode()) {
22931   default:
22932     break;
22933   case X86ISD::PSHUFLW:
22934   case X86ISD::PSHUFHW:
22935     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
22936
22937     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22938       return SDValue(); // We combined away this shuffle, so we're done.
22939
22940     // See if this reduces to a PSHUFD which is no more expensive and can
22941     // combine with more operations. Note that it has to at least flip the
22942     // dwords as otherwise it would have been removed as a no-op.
22943     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22944       int DMask[] = {0, 1, 2, 3};
22945       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22946       DMask[DOffset + 0] = DOffset + 1;
22947       DMask[DOffset + 1] = DOffset + 0;
22948       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22949       V = DAG.getBitcast(DVT, V);
22950       DCI.AddToWorklist(V.getNode());
22951       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22952                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22953       DCI.AddToWorklist(V.getNode());
22954       return DAG.getBitcast(VT, V);
22955     }
22956
22957     // Look for shuffle patterns which can be implemented as a single unpack.
22958     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22959     // only works when we have a PSHUFD followed by two half-shuffles.
22960     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22961         (V.getOpcode() == X86ISD::PSHUFLW ||
22962          V.getOpcode() == X86ISD::PSHUFHW) &&
22963         V.getOpcode() != N.getOpcode() &&
22964         V.hasOneUse()) {
22965       SDValue D = V.getOperand(0);
22966       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22967         D = D.getOperand(0);
22968       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22969         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22970         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22971         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22972         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22973         int WordMask[8];
22974         for (int i = 0; i < 4; ++i) {
22975           WordMask[i + NOffset] = Mask[i] + NOffset;
22976           WordMask[i + VOffset] = VMask[i] + VOffset;
22977         }
22978         // Map the word mask through the DWord mask.
22979         int MappedMask[8];
22980         for (int i = 0; i < 8; ++i)
22981           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22982         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22983             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22984           // We can replace all three shuffles with an unpack.
22985           V = DAG.getBitcast(VT, D.getOperand(0));
22986           DCI.AddToWorklist(V.getNode());
22987           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22988                                                 : X86ISD::UNPCKH,
22989                              DL, VT, V, V);
22990         }
22991       }
22992     }
22993
22994     break;
22995
22996   case X86ISD::PSHUFD:
22997     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22998       return NewN;
22999
23000     break;
23001   }
23002
23003   return SDValue();
23004 }
23005
23006 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23007 ///
23008 /// We combine this directly on the abstract vector shuffle nodes so it is
23009 /// easier to generically match. We also insert dummy vector shuffle nodes for
23010 /// the operands which explicitly discard the lanes which are unused by this
23011 /// operation to try to flow through the rest of the combiner the fact that
23012 /// they're unused.
23013 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23014   SDLoc DL(N);
23015   EVT VT = N->getValueType(0);
23016
23017   // We only handle target-independent shuffles.
23018   // FIXME: It would be easy and harmless to use the target shuffle mask
23019   // extraction tool to support more.
23020   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23021     return SDValue();
23022
23023   auto *SVN = cast<ShuffleVectorSDNode>(N);
23024   ArrayRef<int> Mask = SVN->getMask();
23025   SDValue V1 = N->getOperand(0);
23026   SDValue V2 = N->getOperand(1);
23027
23028   // We require the first shuffle operand to be the SUB node, and the second to
23029   // be the ADD node.
23030   // FIXME: We should support the commuted patterns.
23031   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
23032     return SDValue();
23033
23034   // If there are other uses of these operations we can't fold them.
23035   if (!V1->hasOneUse() || !V2->hasOneUse())
23036     return SDValue();
23037
23038   // Ensure that both operations have the same operands. Note that we can
23039   // commute the FADD operands.
23040   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23041   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23042       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23043     return SDValue();
23044
23045   // We're looking for blends between FADD and FSUB nodes. We insist on these
23046   // nodes being lined up in a specific expected pattern.
23047   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23048         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23049         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23050     return SDValue();
23051
23052   // Only specific types are legal at this point, assert so we notice if and
23053   // when these change.
23054   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23055           VT == MVT::v4f64) &&
23056          "Unknown vector type encountered!");
23057
23058   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23059 }
23060
23061 /// PerformShuffleCombine - Performs several different shuffle combines.
23062 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23063                                      TargetLowering::DAGCombinerInfo &DCI,
23064                                      const X86Subtarget *Subtarget) {
23065   SDLoc dl(N);
23066   SDValue N0 = N->getOperand(0);
23067   SDValue N1 = N->getOperand(1);
23068   EVT VT = N->getValueType(0);
23069
23070   // Don't create instructions with illegal types after legalize types has run.
23071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23072   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23073     return SDValue();
23074
23075   // If we have legalized the vector types, look for blends of FADD and FSUB
23076   // nodes that we can fuse into an ADDSUB node.
23077   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23078     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23079       return AddSub;
23080
23081   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23082   if (Subtarget->hasFp256() && VT.is256BitVector() &&
23083       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23084     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23085
23086   // During Type Legalization, when promoting illegal vector types,
23087   // the backend might introduce new shuffle dag nodes and bitcasts.
23088   //
23089   // This code performs the following transformation:
23090   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23091   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23092   //
23093   // We do this only if both the bitcast and the BINOP dag nodes have
23094   // one use. Also, perform this transformation only if the new binary
23095   // operation is legal. This is to avoid introducing dag nodes that
23096   // potentially need to be further expanded (or custom lowered) into a
23097   // less optimal sequence of dag nodes.
23098   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23099       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23100       N0.getOpcode() == ISD::BITCAST) {
23101     SDValue BC0 = N0.getOperand(0);
23102     EVT SVT = BC0.getValueType();
23103     unsigned Opcode = BC0.getOpcode();
23104     unsigned NumElts = VT.getVectorNumElements();
23105
23106     if (BC0.hasOneUse() && SVT.isVector() &&
23107         SVT.getVectorNumElements() * 2 == NumElts &&
23108         TLI.isOperationLegal(Opcode, VT)) {
23109       bool CanFold = false;
23110       switch (Opcode) {
23111       default : break;
23112       case ISD::ADD :
23113       case ISD::FADD :
23114       case ISD::SUB :
23115       case ISD::FSUB :
23116       case ISD::MUL :
23117       case ISD::FMUL :
23118         CanFold = true;
23119       }
23120
23121       unsigned SVTNumElts = SVT.getVectorNumElements();
23122       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23123       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23124         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23125       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23126         CanFold = SVOp->getMaskElt(i) < 0;
23127
23128       if (CanFold) {
23129         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23130         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23131         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23132         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23133       }
23134     }
23135   }
23136
23137   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23138   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23139   // consecutive, non-overlapping, and in the right order.
23140   SmallVector<SDValue, 16> Elts;
23141   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23142     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23143
23144   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23145     return LD;
23146
23147   if (isTargetShuffle(N->getOpcode())) {
23148     SDValue Shuffle =
23149         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23150     if (Shuffle.getNode())
23151       return Shuffle;
23152
23153     // Try recursively combining arbitrary sequences of x86 shuffle
23154     // instructions into higher-order shuffles. We do this after combining
23155     // specific PSHUF instruction sequences into their minimal form so that we
23156     // can evaluate how many specialized shuffle instructions are involved in
23157     // a particular chain.
23158     SmallVector<int, 1> NonceMask; // Just a placeholder.
23159     NonceMask.push_back(0);
23160     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23161                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23162                                       DCI, Subtarget))
23163       return SDValue(); // This routine will use CombineTo to replace N.
23164   }
23165
23166   return SDValue();
23167 }
23168
23169 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23170 /// specific shuffle of a load can be folded into a single element load.
23171 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23172 /// shuffles have been custom lowered so we need to handle those here.
23173 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23174                                          TargetLowering::DAGCombinerInfo &DCI) {
23175   if (DCI.isBeforeLegalizeOps())
23176     return SDValue();
23177
23178   SDValue InVec = N->getOperand(0);
23179   SDValue EltNo = N->getOperand(1);
23180
23181   if (!isa<ConstantSDNode>(EltNo))
23182     return SDValue();
23183
23184   EVT OriginalVT = InVec.getValueType();
23185
23186   if (InVec.getOpcode() == ISD::BITCAST) {
23187     // Don't duplicate a load with other uses.
23188     if (!InVec.hasOneUse())
23189       return SDValue();
23190     EVT BCVT = InVec.getOperand(0).getValueType();
23191     if (!BCVT.isVector() ||
23192         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23193       return SDValue();
23194     InVec = InVec.getOperand(0);
23195   }
23196
23197   EVT CurrentVT = InVec.getValueType();
23198
23199   if (!isTargetShuffle(InVec.getOpcode()))
23200     return SDValue();
23201
23202   // Don't duplicate a load with other uses.
23203   if (!InVec.hasOneUse())
23204     return SDValue();
23205
23206   SmallVector<int, 16> ShuffleMask;
23207   bool UnaryShuffle;
23208   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23209                             ShuffleMask, UnaryShuffle))
23210     return SDValue();
23211
23212   // Select the input vector, guarding against out of range extract vector.
23213   unsigned NumElems = CurrentVT.getVectorNumElements();
23214   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23215   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23216   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23217                                          : InVec.getOperand(1);
23218
23219   // If inputs to shuffle are the same for both ops, then allow 2 uses
23220   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23221                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23222
23223   if (LdNode.getOpcode() == ISD::BITCAST) {
23224     // Don't duplicate a load with other uses.
23225     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23226       return SDValue();
23227
23228     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23229     LdNode = LdNode.getOperand(0);
23230   }
23231
23232   if (!ISD::isNormalLoad(LdNode.getNode()))
23233     return SDValue();
23234
23235   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23236
23237   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23238     return SDValue();
23239
23240   EVT EltVT = N->getValueType(0);
23241   // If there's a bitcast before the shuffle, check if the load type and
23242   // alignment is valid.
23243   unsigned Align = LN0->getAlignment();
23244   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23245   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23246       EltVT.getTypeForEVT(*DAG.getContext()));
23247
23248   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23249     return SDValue();
23250
23251   // All checks match so transform back to vector_shuffle so that DAG combiner
23252   // can finish the job
23253   SDLoc dl(N);
23254
23255   // Create shuffle node taking into account the case that its a unary shuffle
23256   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23257                                    : InVec.getOperand(1);
23258   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23259                                  InVec.getOperand(0), Shuffle,
23260                                  &ShuffleMask[0]);
23261   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23262   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23263                      EltNo);
23264 }
23265
23266 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23267                                      const X86Subtarget *Subtarget) {
23268   SDValue N0 = N->getOperand(0);
23269   EVT VT = N->getValueType(0);
23270
23271   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23272   // special and don't usually play with other vector types, it's better to
23273   // handle them early to be sure we emit efficient code by avoiding
23274   // store-load conversions.
23275   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23276       N0.getValueType() == MVT::v2i32 &&
23277       isa<ConstantSDNode>(N0.getOperand(1))) {
23278     SDValue N00 = N0->getOperand(0);
23279     if (N0.getConstantOperandVal(1) == 0 && N00.getValueType() == MVT::i32)
23280       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23281   }
23282
23283   // Convert a bitcasted integer logic operation that has one bitcasted
23284   // floating-point operand and one constant operand into a floating-point
23285   // logic operation. This may create a load of the constant, but that is
23286   // cheaper than materializing the constant in an integer register and
23287   // transferring it to an SSE register or transferring the SSE operand to
23288   // integer register and back.
23289   unsigned FPOpcode;
23290   switch (N0.getOpcode()) {
23291     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23292     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23293     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23294     default: return SDValue();
23295   }
23296   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23297        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23298       isa<ConstantSDNode>(N0.getOperand(1)) &&
23299       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23300       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23301     SDValue N000 = N0.getOperand(0).getOperand(0);
23302     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23303     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23304   }
23305
23306   return SDValue();
23307 }
23308
23309 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23310 /// generation and convert it from being a bunch of shuffles and extracts
23311 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23312 /// storing the value and loading scalars back, while for x64 we should
23313 /// use 64-bit extracts and shifts.
23314 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23315                                          TargetLowering::DAGCombinerInfo &DCI) {
23316   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23317     return NewOp;
23318
23319   SDValue InputVector = N->getOperand(0);
23320   SDLoc dl(InputVector);
23321   // Detect mmx to i32 conversion through a v2i32 elt extract.
23322   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23323       N->getValueType(0) == MVT::i32 &&
23324       InputVector.getValueType() == MVT::v2i32) {
23325
23326     // The bitcast source is a direct mmx result.
23327     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23328     if (MMXSrc.getValueType() == MVT::x86mmx)
23329       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23330                          N->getValueType(0),
23331                          InputVector.getNode()->getOperand(0));
23332
23333     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23334     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23335         MMXSrc.getValueType() == MVT::i64) {
23336       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23337       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23338           MMXSrcOp.getValueType() == MVT::v1i64 &&
23339           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23340         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23341                            N->getValueType(0), MMXSrcOp.getOperand(0));
23342     }
23343   }
23344
23345   EVT VT = N->getValueType(0);
23346
23347   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23348       InputVector.getOpcode() == ISD::BITCAST &&
23349       isa<ConstantSDNode>(InputVector.getOperand(0))) {
23350     uint64_t ExtractedElt =
23351         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23352     uint64_t InputValue =
23353         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23354     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23355     return DAG.getConstant(Res, dl, MVT::i1);
23356   }
23357   // Only operate on vectors of 4 elements, where the alternative shuffling
23358   // gets to be more expensive.
23359   if (InputVector.getValueType() != MVT::v4i32)
23360     return SDValue();
23361
23362   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23363   // single use which is a sign-extend or zero-extend, and all elements are
23364   // used.
23365   SmallVector<SDNode *, 4> Uses;
23366   unsigned ExtractedElements = 0;
23367   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23368        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23369     if (UI.getUse().getResNo() != InputVector.getResNo())
23370       return SDValue();
23371
23372     SDNode *Extract = *UI;
23373     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23374       return SDValue();
23375
23376     if (Extract->getValueType(0) != MVT::i32)
23377       return SDValue();
23378     if (!Extract->hasOneUse())
23379       return SDValue();
23380     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23381         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23382       return SDValue();
23383     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23384       return SDValue();
23385
23386     // Record which element was extracted.
23387     ExtractedElements |=
23388       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23389
23390     Uses.push_back(Extract);
23391   }
23392
23393   // If not all the elements were used, this may not be worthwhile.
23394   if (ExtractedElements != 15)
23395     return SDValue();
23396
23397   // Ok, we've now decided to do the transformation.
23398   // If 64-bit shifts are legal, use the extract-shift sequence,
23399   // otherwise bounce the vector off the cache.
23400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23401   SDValue Vals[4];
23402
23403   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23404     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23405     auto &DL = DAG.getDataLayout();
23406     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23407     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23408       DAG.getConstant(0, dl, VecIdxTy));
23409     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23410       DAG.getConstant(1, dl, VecIdxTy));
23411
23412     SDValue ShAmt = DAG.getConstant(
23413         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23414     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23415     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23416       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23417     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23418     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23419       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23420   } else {
23421     // Store the value to a temporary stack slot.
23422     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23423     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23424       MachinePointerInfo(), false, false, 0);
23425
23426     EVT ElementType = InputVector.getValueType().getVectorElementType();
23427     unsigned EltSize = ElementType.getSizeInBits() / 8;
23428
23429     // Replace each use (extract) with a load of the appropriate element.
23430     for (unsigned i = 0; i < 4; ++i) {
23431       uint64_t Offset = EltSize * i;
23432       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23433       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23434
23435       SDValue ScalarAddr =
23436           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23437
23438       // Load the scalar.
23439       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23440                             ScalarAddr, MachinePointerInfo(),
23441                             false, false, false, 0);
23442
23443     }
23444   }
23445
23446   // Replace the extracts
23447   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23448     UE = Uses.end(); UI != UE; ++UI) {
23449     SDNode *Extract = *UI;
23450
23451     SDValue Idx = Extract->getOperand(1);
23452     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23453     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23454   }
23455
23456   // The replacement was made in place; don't return anything.
23457   return SDValue();
23458 }
23459
23460 static SDValue
23461 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23462                                       const X86Subtarget *Subtarget) {
23463   SDLoc dl(N);
23464   SDValue Cond = N->getOperand(0);
23465   SDValue LHS = N->getOperand(1);
23466   SDValue RHS = N->getOperand(2);
23467
23468   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23469     SDValue CondSrc = Cond->getOperand(0);
23470     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23471       Cond = CondSrc->getOperand(0);
23472   }
23473
23474   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23475     return SDValue();
23476
23477   // A vselect where all conditions and data are constants can be optimized into
23478   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23479   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23480       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23481     return SDValue();
23482
23483   unsigned MaskValue = 0;
23484   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23485     return SDValue();
23486
23487   MVT VT = N->getSimpleValueType(0);
23488   unsigned NumElems = VT.getVectorNumElements();
23489   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23490   for (unsigned i = 0; i < NumElems; ++i) {
23491     // Be sure we emit undef where we can.
23492     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23493       ShuffleMask[i] = -1;
23494     else
23495       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23496   }
23497
23498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23499   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23500     return SDValue();
23501   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23502 }
23503
23504 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23505 /// nodes.
23506 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23507                                     TargetLowering::DAGCombinerInfo &DCI,
23508                                     const X86Subtarget *Subtarget) {
23509   SDLoc DL(N);
23510   SDValue Cond = N->getOperand(0);
23511   // Get the LHS/RHS of the select.
23512   SDValue LHS = N->getOperand(1);
23513   SDValue RHS = N->getOperand(2);
23514   EVT VT = LHS.getValueType();
23515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23516
23517   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23518   // instructions match the semantics of the common C idiom x<y?x:y but not
23519   // x<=y?x:y, because of how they handle negative zero (which can be
23520   // ignored in unsafe-math mode).
23521   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23522   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23523       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23524       (Subtarget->hasSSE2() ||
23525        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23526     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23527
23528     unsigned Opcode = 0;
23529     // Check for x CC y ? x : y.
23530     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23531         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23532       switch (CC) {
23533       default: break;
23534       case ISD::SETULT:
23535         // Converting this to a min would handle NaNs incorrectly, and swapping
23536         // the operands would cause it to handle comparisons between positive
23537         // and negative zero incorrectly.
23538         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23539           if (!DAG.getTarget().Options.UnsafeFPMath &&
23540               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23541             break;
23542           std::swap(LHS, RHS);
23543         }
23544         Opcode = X86ISD::FMIN;
23545         break;
23546       case ISD::SETOLE:
23547         // Converting this to a min would handle comparisons between positive
23548         // and negative zero incorrectly.
23549         if (!DAG.getTarget().Options.UnsafeFPMath &&
23550             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23551           break;
23552         Opcode = X86ISD::FMIN;
23553         break;
23554       case ISD::SETULE:
23555         // Converting this to a min would handle both negative zeros and NaNs
23556         // incorrectly, but we can swap the operands to fix both.
23557         std::swap(LHS, RHS);
23558       case ISD::SETOLT:
23559       case ISD::SETLT:
23560       case ISD::SETLE:
23561         Opcode = X86ISD::FMIN;
23562         break;
23563
23564       case ISD::SETOGE:
23565         // Converting this to a max would handle comparisons between positive
23566         // and negative zero incorrectly.
23567         if (!DAG.getTarget().Options.UnsafeFPMath &&
23568             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23569           break;
23570         Opcode = X86ISD::FMAX;
23571         break;
23572       case ISD::SETUGT:
23573         // Converting this to a max would handle NaNs incorrectly, and swapping
23574         // the operands would cause it to handle comparisons between positive
23575         // and negative zero incorrectly.
23576         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23577           if (!DAG.getTarget().Options.UnsafeFPMath &&
23578               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23579             break;
23580           std::swap(LHS, RHS);
23581         }
23582         Opcode = X86ISD::FMAX;
23583         break;
23584       case ISD::SETUGE:
23585         // Converting this to a max would handle both negative zeros and NaNs
23586         // incorrectly, but we can swap the operands to fix both.
23587         std::swap(LHS, RHS);
23588       case ISD::SETOGT:
23589       case ISD::SETGT:
23590       case ISD::SETGE:
23591         Opcode = X86ISD::FMAX;
23592         break;
23593       }
23594     // Check for x CC y ? y : x -- a min/max with reversed arms.
23595     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23596                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23597       switch (CC) {
23598       default: break;
23599       case ISD::SETOGE:
23600         // Converting this to a min would handle comparisons between positive
23601         // and negative zero incorrectly, and swapping the operands would
23602         // cause it to handle NaNs incorrectly.
23603         if (!DAG.getTarget().Options.UnsafeFPMath &&
23604             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23605           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23606             break;
23607           std::swap(LHS, RHS);
23608         }
23609         Opcode = X86ISD::FMIN;
23610         break;
23611       case ISD::SETUGT:
23612         // Converting this to a min would handle NaNs incorrectly.
23613         if (!DAG.getTarget().Options.UnsafeFPMath &&
23614             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23615           break;
23616         Opcode = X86ISD::FMIN;
23617         break;
23618       case ISD::SETUGE:
23619         // Converting this to a min would handle both negative zeros and NaNs
23620         // incorrectly, but we can swap the operands to fix both.
23621         std::swap(LHS, RHS);
23622       case ISD::SETOGT:
23623       case ISD::SETGT:
23624       case ISD::SETGE:
23625         Opcode = X86ISD::FMIN;
23626         break;
23627
23628       case ISD::SETULT:
23629         // Converting this to a max would handle NaNs incorrectly.
23630         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23631           break;
23632         Opcode = X86ISD::FMAX;
23633         break;
23634       case ISD::SETOLE:
23635         // Converting this to a max would handle comparisons between positive
23636         // and negative zero incorrectly, and swapping the operands would
23637         // cause it to handle NaNs incorrectly.
23638         if (!DAG.getTarget().Options.UnsafeFPMath &&
23639             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23640           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23641             break;
23642           std::swap(LHS, RHS);
23643         }
23644         Opcode = X86ISD::FMAX;
23645         break;
23646       case ISD::SETULE:
23647         // Converting this to a max would handle both negative zeros and NaNs
23648         // incorrectly, but we can swap the operands to fix both.
23649         std::swap(LHS, RHS);
23650       case ISD::SETOLT:
23651       case ISD::SETLT:
23652       case ISD::SETLE:
23653         Opcode = X86ISD::FMAX;
23654         break;
23655       }
23656     }
23657
23658     if (Opcode)
23659       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23660   }
23661
23662   EVT CondVT = Cond.getValueType();
23663   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23664       CondVT.getVectorElementType() == MVT::i1) {
23665     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23666     // lowering on KNL. In this case we convert it to
23667     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23668     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23669     // Since SKX these selects have a proper lowering.
23670     EVT OpVT = LHS.getValueType();
23671     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23672         (OpVT.getVectorElementType() == MVT::i8 ||
23673          OpVT.getVectorElementType() == MVT::i16) &&
23674         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23675       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23676       DCI.AddToWorklist(Cond.getNode());
23677       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23678     }
23679   }
23680   // If this is a select between two integer constants, try to do some
23681   // optimizations.
23682   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23683     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23684       // Don't do this for crazy integer types.
23685       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23686         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23687         // so that TrueC (the true value) is larger than FalseC.
23688         bool NeedsCondInvert = false;
23689
23690         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23691             // Efficiently invertible.
23692             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23693              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23694               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23695           NeedsCondInvert = true;
23696           std::swap(TrueC, FalseC);
23697         }
23698
23699         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23700         if (FalseC->getAPIntValue() == 0 &&
23701             TrueC->getAPIntValue().isPowerOf2()) {
23702           if (NeedsCondInvert) // Invert the condition if needed.
23703             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23704                                DAG.getConstant(1, DL, Cond.getValueType()));
23705
23706           // Zero extend the condition if needed.
23707           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23708
23709           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23710           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23711                              DAG.getConstant(ShAmt, DL, MVT::i8));
23712         }
23713
23714         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23715         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23716           if (NeedsCondInvert) // Invert the condition if needed.
23717             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23718                                DAG.getConstant(1, DL, Cond.getValueType()));
23719
23720           // Zero extend the condition if needed.
23721           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23722                              FalseC->getValueType(0), Cond);
23723           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23724                              SDValue(FalseC, 0));
23725         }
23726
23727         // Optimize cases that will turn into an LEA instruction.  This requires
23728         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23729         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23730           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23731           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23732
23733           bool isFastMultiplier = false;
23734           if (Diff < 10) {
23735             switch ((unsigned char)Diff) {
23736               default: break;
23737               case 1:  // result = add base, cond
23738               case 2:  // result = lea base(    , cond*2)
23739               case 3:  // result = lea base(cond, cond*2)
23740               case 4:  // result = lea base(    , cond*4)
23741               case 5:  // result = lea base(cond, cond*4)
23742               case 8:  // result = lea base(    , cond*8)
23743               case 9:  // result = lea base(cond, cond*8)
23744                 isFastMultiplier = true;
23745                 break;
23746             }
23747           }
23748
23749           if (isFastMultiplier) {
23750             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23751             if (NeedsCondInvert) // Invert the condition if needed.
23752               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23753                                  DAG.getConstant(1, DL, Cond.getValueType()));
23754
23755             // Zero extend the condition if needed.
23756             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23757                                Cond);
23758             // Scale the condition by the difference.
23759             if (Diff != 1)
23760               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23761                                  DAG.getConstant(Diff, DL,
23762                                                  Cond.getValueType()));
23763
23764             // Add the base if non-zero.
23765             if (FalseC->getAPIntValue() != 0)
23766               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23767                                  SDValue(FalseC, 0));
23768             return Cond;
23769           }
23770         }
23771       }
23772   }
23773
23774   // Canonicalize max and min:
23775   // (x > y) ? x : y -> (x >= y) ? x : y
23776   // (x < y) ? x : y -> (x <= y) ? x : y
23777   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23778   // the need for an extra compare
23779   // against zero. e.g.
23780   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23781   // subl   %esi, %edi
23782   // testl  %edi, %edi
23783   // movl   $0, %eax
23784   // cmovgl %edi, %eax
23785   // =>
23786   // xorl   %eax, %eax
23787   // subl   %esi, $edi
23788   // cmovsl %eax, %edi
23789   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23790       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23791       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23792     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23793     switch (CC) {
23794     default: break;
23795     case ISD::SETLT:
23796     case ISD::SETGT: {
23797       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23798       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23799                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23800       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23801     }
23802     }
23803   }
23804
23805   // Early exit check
23806   if (!TLI.isTypeLegal(VT))
23807     return SDValue();
23808
23809   // Match VSELECTs into subs with unsigned saturation.
23810   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23811       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23812       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23813        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23814     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23815
23816     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23817     // left side invert the predicate to simplify logic below.
23818     SDValue Other;
23819     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23820       Other = RHS;
23821       CC = ISD::getSetCCInverse(CC, true);
23822     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23823       Other = LHS;
23824     }
23825
23826     if (Other.getNode() && Other->getNumOperands() == 2 &&
23827         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23828       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23829       SDValue CondRHS = Cond->getOperand(1);
23830
23831       // Look for a general sub with unsigned saturation first.
23832       // x >= y ? x-y : 0 --> subus x, y
23833       // x >  y ? x-y : 0 --> subus x, y
23834       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23835           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23836         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23837
23838       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23839         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23840           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23841             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23842               // If the RHS is a constant we have to reverse the const
23843               // canonicalization.
23844               // x > C-1 ? x+-C : 0 --> subus x, C
23845               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23846                   CondRHSConst->getAPIntValue() ==
23847                       (-OpRHSConst->getAPIntValue() - 1))
23848                 return DAG.getNode(
23849                     X86ISD::SUBUS, DL, VT, OpLHS,
23850                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23851
23852           // Another special case: If C was a sign bit, the sub has been
23853           // canonicalized into a xor.
23854           // FIXME: Would it be better to use computeKnownBits to determine
23855           //        whether it's safe to decanonicalize the xor?
23856           // x s< 0 ? x^C : 0 --> subus x, C
23857           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23858               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23859               OpRHSConst->getAPIntValue().isSignBit())
23860             // Note that we have to rebuild the RHS constant here to ensure we
23861             // don't rely on particular values of undef lanes.
23862             return DAG.getNode(
23863                 X86ISD::SUBUS, DL, VT, OpLHS,
23864                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23865         }
23866     }
23867   }
23868
23869   // Simplify vector selection if condition value type matches vselect
23870   // operand type
23871   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23872     assert(Cond.getValueType().isVector() &&
23873            "vector select expects a vector selector!");
23874
23875     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23876     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23877
23878     // Try invert the condition if true value is not all 1s and false value
23879     // is not all 0s.
23880     if (!TValIsAllOnes && !FValIsAllZeros &&
23881         // Check if the selector will be produced by CMPP*/PCMP*
23882         Cond.getOpcode() == ISD::SETCC &&
23883         // Check if SETCC has already been promoted
23884         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23885             CondVT) {
23886       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23887       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23888
23889       if (TValIsAllZeros || FValIsAllOnes) {
23890         SDValue CC = Cond.getOperand(2);
23891         ISD::CondCode NewCC =
23892           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23893                                Cond.getOperand(0).getValueType().isInteger());
23894         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23895         std::swap(LHS, RHS);
23896         TValIsAllOnes = FValIsAllOnes;
23897         FValIsAllZeros = TValIsAllZeros;
23898       }
23899     }
23900
23901     if (TValIsAllOnes || FValIsAllZeros) {
23902       SDValue Ret;
23903
23904       if (TValIsAllOnes && FValIsAllZeros)
23905         Ret = Cond;
23906       else if (TValIsAllOnes)
23907         Ret =
23908             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23909       else if (FValIsAllZeros)
23910         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23911                           DAG.getBitcast(CondVT, LHS));
23912
23913       return DAG.getBitcast(VT, Ret);
23914     }
23915   }
23916
23917   // We should generate an X86ISD::BLENDI from a vselect if its argument
23918   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23919   // constants. This specific pattern gets generated when we split a
23920   // selector for a 512 bit vector in a machine without AVX512 (but with
23921   // 256-bit vectors), during legalization:
23922   //
23923   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23924   //
23925   // Iff we find this pattern and the build_vectors are built from
23926   // constants, we translate the vselect into a shuffle_vector that we
23927   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23928   if ((N->getOpcode() == ISD::VSELECT ||
23929        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23930       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23931     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23932     if (Shuffle.getNode())
23933       return Shuffle;
23934   }
23935
23936   // If this is a *dynamic* select (non-constant condition) and we can match
23937   // this node with one of the variable blend instructions, restructure the
23938   // condition so that the blends can use the high bit of each element and use
23939   // SimplifyDemandedBits to simplify the condition operand.
23940   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23941       !DCI.isBeforeLegalize() &&
23942       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23943     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
23944
23945     // Don't optimize vector selects that map to mask-registers.
23946     if (BitWidth == 1)
23947       return SDValue();
23948
23949     // We can only handle the cases where VSELECT is directly legal on the
23950     // subtarget. We custom lower VSELECT nodes with constant conditions and
23951     // this makes it hard to see whether a dynamic VSELECT will correctly
23952     // lower, so we both check the operation's status and explicitly handle the
23953     // cases where a *dynamic* blend will fail even though a constant-condition
23954     // blend could be custom lowered.
23955     // FIXME: We should find a better way to handle this class of problems.
23956     // Potentially, we should combine constant-condition vselect nodes
23957     // pre-legalization into shuffles and not mark as many types as custom
23958     // lowered.
23959     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23960       return SDValue();
23961     // FIXME: We don't support i16-element blends currently. We could and
23962     // should support them by making *all* the bits in the condition be set
23963     // rather than just the high bit and using an i8-element blend.
23964     if (VT.getVectorElementType() == MVT::i16)
23965       return SDValue();
23966     // Dynamic blending was only available from SSE4.1 onward.
23967     if (VT.is128BitVector() && !Subtarget->hasSSE41())
23968       return SDValue();
23969     // Byte blends are only available in AVX2
23970     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
23971       return SDValue();
23972
23973     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23974     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23975
23976     APInt KnownZero, KnownOne;
23977     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23978                                           DCI.isBeforeLegalizeOps());
23979     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23980         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23981                                  TLO)) {
23982       // If we changed the computation somewhere in the DAG, this change
23983       // will affect all users of Cond.
23984       // Make sure it is fine and update all the nodes so that we do not
23985       // use the generic VSELECT anymore. Otherwise, we may perform
23986       // wrong optimizations as we messed up with the actual expectation
23987       // for the vector boolean values.
23988       if (Cond != TLO.Old) {
23989         // Check all uses of that condition operand to check whether it will be
23990         // consumed by non-BLEND instructions, which may depend on all bits are
23991         // set properly.
23992         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23993              I != E; ++I)
23994           if (I->getOpcode() != ISD::VSELECT)
23995             // TODO: Add other opcodes eventually lowered into BLEND.
23996             return SDValue();
23997
23998         // Update all the users of the condition, before committing the change,
23999         // so that the VSELECT optimizations that expect the correct vector
24000         // boolean value will not be triggered.
24001         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24002              I != E; ++I)
24003           DAG.ReplaceAllUsesOfValueWith(
24004               SDValue(*I, 0),
24005               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24006                           Cond, I->getOperand(1), I->getOperand(2)));
24007         DCI.CommitTargetLoweringOpt(TLO);
24008         return SDValue();
24009       }
24010       // At this point, only Cond is changed. Change the condition
24011       // just for N to keep the opportunity to optimize all other
24012       // users their own way.
24013       DAG.ReplaceAllUsesOfValueWith(
24014           SDValue(N, 0),
24015           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24016                       TLO.New, N->getOperand(1), N->getOperand(2)));
24017       return SDValue();
24018     }
24019   }
24020
24021   return SDValue();
24022 }
24023
24024 // Check whether a boolean test is testing a boolean value generated by
24025 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24026 // code.
24027 //
24028 // Simplify the following patterns:
24029 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24030 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24031 // to (Op EFLAGS Cond)
24032 //
24033 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24034 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24035 // to (Op EFLAGS !Cond)
24036 //
24037 // where Op could be BRCOND or CMOV.
24038 //
24039 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24040   // Quit if not CMP and SUB with its value result used.
24041   if (Cmp.getOpcode() != X86ISD::CMP &&
24042       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24043       return SDValue();
24044
24045   // Quit if not used as a boolean value.
24046   if (CC != X86::COND_E && CC != X86::COND_NE)
24047     return SDValue();
24048
24049   // Check CMP operands. One of them should be 0 or 1 and the other should be
24050   // an SetCC or extended from it.
24051   SDValue Op1 = Cmp.getOperand(0);
24052   SDValue Op2 = Cmp.getOperand(1);
24053
24054   SDValue SetCC;
24055   const ConstantSDNode* C = nullptr;
24056   bool needOppositeCond = (CC == X86::COND_E);
24057   bool checkAgainstTrue = false; // Is it a comparison against 1?
24058
24059   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24060     SetCC = Op2;
24061   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24062     SetCC = Op1;
24063   else // Quit if all operands are not constants.
24064     return SDValue();
24065
24066   if (C->getZExtValue() == 1) {
24067     needOppositeCond = !needOppositeCond;
24068     checkAgainstTrue = true;
24069   } else if (C->getZExtValue() != 0)
24070     // Quit if the constant is neither 0 or 1.
24071     return SDValue();
24072
24073   bool truncatedToBoolWithAnd = false;
24074   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24075   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24076          SetCC.getOpcode() == ISD::TRUNCATE ||
24077          SetCC.getOpcode() == ISD::AND) {
24078     if (SetCC.getOpcode() == ISD::AND) {
24079       int OpIdx = -1;
24080       ConstantSDNode *CS;
24081       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
24082           CS->getZExtValue() == 1)
24083         OpIdx = 1;
24084       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
24085           CS->getZExtValue() == 1)
24086         OpIdx = 0;
24087       if (OpIdx == -1)
24088         break;
24089       SetCC = SetCC.getOperand(OpIdx);
24090       truncatedToBoolWithAnd = true;
24091     } else
24092       SetCC = SetCC.getOperand(0);
24093   }
24094
24095   switch (SetCC.getOpcode()) {
24096   case X86ISD::SETCC_CARRY:
24097     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24098     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24099     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24100     // truncated to i1 using 'and'.
24101     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24102       break;
24103     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24104            "Invalid use of SETCC_CARRY!");
24105     // FALL THROUGH
24106   case X86ISD::SETCC:
24107     // Set the condition code or opposite one if necessary.
24108     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24109     if (needOppositeCond)
24110       CC = X86::GetOppositeBranchCondition(CC);
24111     return SetCC.getOperand(1);
24112   case X86ISD::CMOV: {
24113     // Check whether false/true value has canonical one, i.e. 0 or 1.
24114     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24115     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24116     // Quit if true value is not a constant.
24117     if (!TVal)
24118       return SDValue();
24119     // Quit if false value is not a constant.
24120     if (!FVal) {
24121       SDValue Op = SetCC.getOperand(0);
24122       // Skip 'zext' or 'trunc' node.
24123       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24124           Op.getOpcode() == ISD::TRUNCATE)
24125         Op = Op.getOperand(0);
24126       // A special case for rdrand/rdseed, where 0 is set if false cond is
24127       // found.
24128       if ((Op.getOpcode() != X86ISD::RDRAND &&
24129            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24130         return SDValue();
24131     }
24132     // Quit if false value is not the constant 0 or 1.
24133     bool FValIsFalse = true;
24134     if (FVal && FVal->getZExtValue() != 0) {
24135       if (FVal->getZExtValue() != 1)
24136         return SDValue();
24137       // If FVal is 1, opposite cond is needed.
24138       needOppositeCond = !needOppositeCond;
24139       FValIsFalse = false;
24140     }
24141     // Quit if TVal is not the constant opposite of FVal.
24142     if (FValIsFalse && TVal->getZExtValue() != 1)
24143       return SDValue();
24144     if (!FValIsFalse && TVal->getZExtValue() != 0)
24145       return SDValue();
24146     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24147     if (needOppositeCond)
24148       CC = X86::GetOppositeBranchCondition(CC);
24149     return SetCC.getOperand(3);
24150   }
24151   }
24152
24153   return SDValue();
24154 }
24155
24156 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24157 /// Match:
24158 ///   (X86or (X86setcc) (X86setcc))
24159 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24160 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24161                                            X86::CondCode &CC1, SDValue &Flags,
24162                                            bool &isAnd) {
24163   if (Cond->getOpcode() == X86ISD::CMP) {
24164     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24165     if (!CondOp1C || !CondOp1C->isNullValue())
24166       return false;
24167
24168     Cond = Cond->getOperand(0);
24169   }
24170
24171   isAnd = false;
24172
24173   SDValue SetCC0, SetCC1;
24174   switch (Cond->getOpcode()) {
24175   default: return false;
24176   case ISD::AND:
24177   case X86ISD::AND:
24178     isAnd = true;
24179     // fallthru
24180   case ISD::OR:
24181   case X86ISD::OR:
24182     SetCC0 = Cond->getOperand(0);
24183     SetCC1 = Cond->getOperand(1);
24184     break;
24185   };
24186
24187   // Make sure we have SETCC nodes, using the same flags value.
24188   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24189       SetCC1.getOpcode() != X86ISD::SETCC ||
24190       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24191     return false;
24192
24193   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24194   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24195   Flags = SetCC0->getOperand(1);
24196   return true;
24197 }
24198
24199 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24200 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24201                                   TargetLowering::DAGCombinerInfo &DCI,
24202                                   const X86Subtarget *Subtarget) {
24203   SDLoc DL(N);
24204
24205   // If the flag operand isn't dead, don't touch this CMOV.
24206   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24207     return SDValue();
24208
24209   SDValue FalseOp = N->getOperand(0);
24210   SDValue TrueOp = N->getOperand(1);
24211   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24212   SDValue Cond = N->getOperand(3);
24213
24214   if (CC == X86::COND_E || CC == X86::COND_NE) {
24215     switch (Cond.getOpcode()) {
24216     default: break;
24217     case X86ISD::BSR:
24218     case X86ISD::BSF:
24219       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24220       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24221         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24222     }
24223   }
24224
24225   SDValue Flags;
24226
24227   Flags = checkBoolTestSetCCCombine(Cond, CC);
24228   if (Flags.getNode() &&
24229       // Extra check as FCMOV only supports a subset of X86 cond.
24230       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24231     SDValue Ops[] = { FalseOp, TrueOp,
24232                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24233     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24234   }
24235
24236   // If this is a select between two integer constants, try to do some
24237   // optimizations.  Note that the operands are ordered the opposite of SELECT
24238   // operands.
24239   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24240     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24241       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24242       // larger than FalseC (the false value).
24243       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24244         CC = X86::GetOppositeBranchCondition(CC);
24245         std::swap(TrueC, FalseC);
24246         std::swap(TrueOp, FalseOp);
24247       }
24248
24249       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24250       // This is efficient for any integer data type (including i8/i16) and
24251       // shift amount.
24252       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24253         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24254                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24255
24256         // Zero extend the condition if needed.
24257         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24258
24259         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24260         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24261                            DAG.getConstant(ShAmt, DL, MVT::i8));
24262         if (N->getNumValues() == 2)  // Dead flag value?
24263           return DCI.CombineTo(N, Cond, SDValue());
24264         return Cond;
24265       }
24266
24267       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24268       // for any integer data type, including i8/i16.
24269       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24270         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24271                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24272
24273         // Zero extend the condition if needed.
24274         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24275                            FalseC->getValueType(0), Cond);
24276         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24277                            SDValue(FalseC, 0));
24278
24279         if (N->getNumValues() == 2)  // Dead flag value?
24280           return DCI.CombineTo(N, Cond, SDValue());
24281         return Cond;
24282       }
24283
24284       // Optimize cases that will turn into an LEA instruction.  This requires
24285       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24286       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24287         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24288         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24289
24290         bool isFastMultiplier = false;
24291         if (Diff < 10) {
24292           switch ((unsigned char)Diff) {
24293           default: break;
24294           case 1:  // result = add base, cond
24295           case 2:  // result = lea base(    , cond*2)
24296           case 3:  // result = lea base(cond, cond*2)
24297           case 4:  // result = lea base(    , cond*4)
24298           case 5:  // result = lea base(cond, cond*4)
24299           case 8:  // result = lea base(    , cond*8)
24300           case 9:  // result = lea base(cond, cond*8)
24301             isFastMultiplier = true;
24302             break;
24303           }
24304         }
24305
24306         if (isFastMultiplier) {
24307           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24308           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24309                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24310           // Zero extend the condition if needed.
24311           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24312                              Cond);
24313           // Scale the condition by the difference.
24314           if (Diff != 1)
24315             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24316                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24317
24318           // Add the base if non-zero.
24319           if (FalseC->getAPIntValue() != 0)
24320             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24321                                SDValue(FalseC, 0));
24322           if (N->getNumValues() == 2)  // Dead flag value?
24323             return DCI.CombineTo(N, Cond, SDValue());
24324           return Cond;
24325         }
24326       }
24327     }
24328   }
24329
24330   // Handle these cases:
24331   //   (select (x != c), e, c) -> select (x != c), e, x),
24332   //   (select (x == c), c, e) -> select (x == c), x, e)
24333   // where the c is an integer constant, and the "select" is the combination
24334   // of CMOV and CMP.
24335   //
24336   // The rationale for this change is that the conditional-move from a constant
24337   // needs two instructions, however, conditional-move from a register needs
24338   // only one instruction.
24339   //
24340   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24341   //  some instruction-combining opportunities. This opt needs to be
24342   //  postponed as late as possible.
24343   //
24344   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24345     // the DCI.xxxx conditions are provided to postpone the optimization as
24346     // late as possible.
24347
24348     ConstantSDNode *CmpAgainst = nullptr;
24349     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24350         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24351         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24352
24353       if (CC == X86::COND_NE &&
24354           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24355         CC = X86::GetOppositeBranchCondition(CC);
24356         std::swap(TrueOp, FalseOp);
24357       }
24358
24359       if (CC == X86::COND_E &&
24360           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24361         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24362                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24363         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24364       }
24365     }
24366   }
24367
24368   // Fold and/or of setcc's to double CMOV:
24369   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24370   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24371   //
24372   // This combine lets us generate:
24373   //   cmovcc1 (jcc1 if we don't have CMOV)
24374   //   cmovcc2 (same)
24375   // instead of:
24376   //   setcc1
24377   //   setcc2
24378   //   and/or
24379   //   cmovne (jne if we don't have CMOV)
24380   // When we can't use the CMOV instruction, it might increase branch
24381   // mispredicts.
24382   // When we can use CMOV, or when there is no mispredict, this improves
24383   // throughput and reduces register pressure.
24384   //
24385   if (CC == X86::COND_NE) {
24386     SDValue Flags;
24387     X86::CondCode CC0, CC1;
24388     bool isAndSetCC;
24389     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24390       if (isAndSetCC) {
24391         std::swap(FalseOp, TrueOp);
24392         CC0 = X86::GetOppositeBranchCondition(CC0);
24393         CC1 = X86::GetOppositeBranchCondition(CC1);
24394       }
24395
24396       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24397         Flags};
24398       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24399       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24400       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24401       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24402       return CMOV;
24403     }
24404   }
24405
24406   return SDValue();
24407 }
24408
24409 /// PerformMulCombine - Optimize a single multiply with constant into two
24410 /// in order to implement it with two cheaper instructions, e.g.
24411 /// LEA + SHL, LEA + LEA.
24412 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24413                                  TargetLowering::DAGCombinerInfo &DCI) {
24414   // An imul is usually smaller than the alternative sequence.
24415   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24416     return SDValue();
24417
24418   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24419     return SDValue();
24420
24421   EVT VT = N->getValueType(0);
24422   if (VT != MVT::i64 && VT != MVT::i32)
24423     return SDValue();
24424
24425   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24426   if (!C)
24427     return SDValue();
24428   uint64_t MulAmt = C->getZExtValue();
24429   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24430     return SDValue();
24431
24432   uint64_t MulAmt1 = 0;
24433   uint64_t MulAmt2 = 0;
24434   if ((MulAmt % 9) == 0) {
24435     MulAmt1 = 9;
24436     MulAmt2 = MulAmt / 9;
24437   } else if ((MulAmt % 5) == 0) {
24438     MulAmt1 = 5;
24439     MulAmt2 = MulAmt / 5;
24440   } else if ((MulAmt % 3) == 0) {
24441     MulAmt1 = 3;
24442     MulAmt2 = MulAmt / 3;
24443   }
24444   if (MulAmt2 &&
24445       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24446     SDLoc DL(N);
24447
24448     if (isPowerOf2_64(MulAmt2) &&
24449         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24450       // If second multiplifer is pow2, issue it first. We want the multiply by
24451       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24452       // is an add.
24453       std::swap(MulAmt1, MulAmt2);
24454
24455     SDValue NewMul;
24456     if (isPowerOf2_64(MulAmt1))
24457       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24458                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24459     else
24460       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24461                            DAG.getConstant(MulAmt1, DL, VT));
24462
24463     if (isPowerOf2_64(MulAmt2))
24464       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24465                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24466     else
24467       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24468                            DAG.getConstant(MulAmt2, DL, VT));
24469
24470     // Do not add new nodes to DAG combiner worklist.
24471     DCI.CombineTo(N, NewMul, false);
24472   }
24473   return SDValue();
24474 }
24475
24476 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24477   SDValue N0 = N->getOperand(0);
24478   SDValue N1 = N->getOperand(1);
24479   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24480   EVT VT = N0.getValueType();
24481
24482   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24483   // since the result of setcc_c is all zero's or all ones.
24484   if (VT.isInteger() && !VT.isVector() &&
24485       N1C && N0.getOpcode() == ISD::AND &&
24486       N0.getOperand(1).getOpcode() == ISD::Constant) {
24487     SDValue N00 = N0.getOperand(0);
24488     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24489     APInt ShAmt = N1C->getAPIntValue();
24490     Mask = Mask.shl(ShAmt);
24491     bool MaskOK = false;
24492     // We can handle cases concerning bit-widening nodes containing setcc_c if
24493     // we carefully interrogate the mask to make sure we are semantics
24494     // preserving.
24495     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24496     // of the underlying setcc_c operation if the setcc_c was zero extended.
24497     // Consider the following example:
24498     //   zext(setcc_c)                 -> i32 0x0000FFFF
24499     //   c1                            -> i32 0x0000FFFF
24500     //   c2                            -> i32 0x00000001
24501     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24502     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24503     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24504       MaskOK = true;
24505     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24506                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24507       MaskOK = true;
24508     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24509                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24510                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24511       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24512     }
24513     if (MaskOK && Mask != 0) {
24514       SDLoc DL(N);
24515       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24516     }
24517   }
24518
24519   // Hardware support for vector shifts is sparse which makes us scalarize the
24520   // vector operations in many cases. Also, on sandybridge ADD is faster than
24521   // shl.
24522   // (shl V, 1) -> add V,V
24523   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24524     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24525       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24526       // We shift all of the values by one. In many cases we do not have
24527       // hardware support for this operation. This is better expressed as an ADD
24528       // of two values.
24529       if (N1SplatC->getAPIntValue() == 1)
24530         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24531     }
24532
24533   return SDValue();
24534 }
24535
24536 /// \brief Returns a vector of 0s if the node in input is a vector logical
24537 /// shift by a constant amount which is known to be bigger than or equal
24538 /// to the vector element size in bits.
24539 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24540                                       const X86Subtarget *Subtarget) {
24541   EVT VT = N->getValueType(0);
24542
24543   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24544       (!Subtarget->hasInt256() ||
24545        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24546     return SDValue();
24547
24548   SDValue Amt = N->getOperand(1);
24549   SDLoc DL(N);
24550   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24551     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24552       APInt ShiftAmt = AmtSplat->getAPIntValue();
24553       unsigned MaxAmount =
24554         VT.getSimpleVT().getVectorElementType().getSizeInBits();
24555
24556       // SSE2/AVX2 logical shifts always return a vector of 0s
24557       // if the shift amount is bigger than or equal to
24558       // the element size. The constant shift amount will be
24559       // encoded as a 8-bit immediate.
24560       if (ShiftAmt.trunc(8).uge(MaxAmount))
24561         return getZeroVector(VT, Subtarget, DAG, DL);
24562     }
24563
24564   return SDValue();
24565 }
24566
24567 /// PerformShiftCombine - Combine shifts.
24568 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24569                                    TargetLowering::DAGCombinerInfo &DCI,
24570                                    const X86Subtarget *Subtarget) {
24571   if (N->getOpcode() == ISD::SHL)
24572     if (SDValue V = PerformSHLCombine(N, DAG))
24573       return V;
24574
24575   // Try to fold this logical shift into a zero vector.
24576   if (N->getOpcode() != ISD::SRA)
24577     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24578       return V;
24579
24580   return SDValue();
24581 }
24582
24583 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24584 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24585 // and friends.  Likewise for OR -> CMPNEQSS.
24586 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24587                             TargetLowering::DAGCombinerInfo &DCI,
24588                             const X86Subtarget *Subtarget) {
24589   unsigned opcode;
24590
24591   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24592   // we're requiring SSE2 for both.
24593   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24594     SDValue N0 = N->getOperand(0);
24595     SDValue N1 = N->getOperand(1);
24596     SDValue CMP0 = N0->getOperand(1);
24597     SDValue CMP1 = N1->getOperand(1);
24598     SDLoc DL(N);
24599
24600     // The SETCCs should both refer to the same CMP.
24601     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24602       return SDValue();
24603
24604     SDValue CMP00 = CMP0->getOperand(0);
24605     SDValue CMP01 = CMP0->getOperand(1);
24606     EVT     VT    = CMP00.getValueType();
24607
24608     if (VT == MVT::f32 || VT == MVT::f64) {
24609       bool ExpectingFlags = false;
24610       // Check for any users that want flags:
24611       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24612            !ExpectingFlags && UI != UE; ++UI)
24613         switch (UI->getOpcode()) {
24614         default:
24615         case ISD::BR_CC:
24616         case ISD::BRCOND:
24617         case ISD::SELECT:
24618           ExpectingFlags = true;
24619           break;
24620         case ISD::CopyToReg:
24621         case ISD::SIGN_EXTEND:
24622         case ISD::ZERO_EXTEND:
24623         case ISD::ANY_EXTEND:
24624           break;
24625         }
24626
24627       if (!ExpectingFlags) {
24628         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24629         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24630
24631         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24632           X86::CondCode tmp = cc0;
24633           cc0 = cc1;
24634           cc1 = tmp;
24635         }
24636
24637         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24638             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24639           // FIXME: need symbolic constants for these magic numbers.
24640           // See X86ATTInstPrinter.cpp:printSSECC().
24641           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24642           if (Subtarget->hasAVX512()) {
24643             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24644                                          CMP01,
24645                                          DAG.getConstant(x86cc, DL, MVT::i8));
24646             if (N->getValueType(0) != MVT::i1)
24647               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24648                                  FSetCC);
24649             return FSetCC;
24650           }
24651           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24652                                               CMP00.getValueType(), CMP00, CMP01,
24653                                               DAG.getConstant(x86cc, DL,
24654                                                               MVT::i8));
24655
24656           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24657           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24658
24659           if (is64BitFP && !Subtarget->is64Bit()) {
24660             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24661             // 64-bit integer, since that's not a legal type. Since
24662             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24663             // bits, but can do this little dance to extract the lowest 32 bits
24664             // and work with those going forward.
24665             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24666                                            OnesOrZeroesF);
24667             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24668             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24669                                         Vector32, DAG.getIntPtrConstant(0, DL));
24670             IntVT = MVT::i32;
24671           }
24672
24673           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24674           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24675                                       DAG.getConstant(1, DL, IntVT));
24676           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24677                                               ANDed);
24678           return OneBitOfTruth;
24679         }
24680       }
24681     }
24682   }
24683   return SDValue();
24684 }
24685
24686 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24687 /// so it can be folded inside ANDNP.
24688 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24689   EVT VT = N->getValueType(0);
24690
24691   // Match direct AllOnes for 128 and 256-bit vectors
24692   if (ISD::isBuildVectorAllOnes(N))
24693     return true;
24694
24695   // Look through a bit convert.
24696   if (N->getOpcode() == ISD::BITCAST)
24697     N = N->getOperand(0).getNode();
24698
24699   // Sometimes the operand may come from a insert_subvector building a 256-bit
24700   // allones vector
24701   if (VT.is256BitVector() &&
24702       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24703     SDValue V1 = N->getOperand(0);
24704     SDValue V2 = N->getOperand(1);
24705
24706     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24707         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24708         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24709         ISD::isBuildVectorAllOnes(V2.getNode()))
24710       return true;
24711   }
24712
24713   return false;
24714 }
24715
24716 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24717 // register. In most cases we actually compare or select YMM-sized registers
24718 // and mixing the two types creates horrible code. This method optimizes
24719 // some of the transition sequences.
24720 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24721                                  TargetLowering::DAGCombinerInfo &DCI,
24722                                  const X86Subtarget *Subtarget) {
24723   EVT VT = N->getValueType(0);
24724   if (!VT.is256BitVector())
24725     return SDValue();
24726
24727   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24728           N->getOpcode() == ISD::ZERO_EXTEND ||
24729           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24730
24731   SDValue Narrow = N->getOperand(0);
24732   EVT NarrowVT = Narrow->getValueType(0);
24733   if (!NarrowVT.is128BitVector())
24734     return SDValue();
24735
24736   if (Narrow->getOpcode() != ISD::XOR &&
24737       Narrow->getOpcode() != ISD::AND &&
24738       Narrow->getOpcode() != ISD::OR)
24739     return SDValue();
24740
24741   SDValue N0  = Narrow->getOperand(0);
24742   SDValue N1  = Narrow->getOperand(1);
24743   SDLoc DL(Narrow);
24744
24745   // The Left side has to be a trunc.
24746   if (N0.getOpcode() != ISD::TRUNCATE)
24747     return SDValue();
24748
24749   // The type of the truncated inputs.
24750   EVT WideVT = N0->getOperand(0)->getValueType(0);
24751   if (WideVT != VT)
24752     return SDValue();
24753
24754   // The right side has to be a 'trunc' or a constant vector.
24755   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24756   ConstantSDNode *RHSConstSplat = nullptr;
24757   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24758     RHSConstSplat = RHSBV->getConstantSplatNode();
24759   if (!RHSTrunc && !RHSConstSplat)
24760     return SDValue();
24761
24762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24763
24764   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24765     return SDValue();
24766
24767   // Set N0 and N1 to hold the inputs to the new wide operation.
24768   N0 = N0->getOperand(0);
24769   if (RHSConstSplat) {
24770     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
24771                      SDValue(RHSConstSplat, 0));
24772     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24773     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24774   } else if (RHSTrunc) {
24775     N1 = N1->getOperand(0);
24776   }
24777
24778   // Generate the wide operation.
24779   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24780   unsigned Opcode = N->getOpcode();
24781   switch (Opcode) {
24782   case ISD::ANY_EXTEND:
24783     return Op;
24784   case ISD::ZERO_EXTEND: {
24785     unsigned InBits = NarrowVT.getScalarSizeInBits();
24786     APInt Mask = APInt::getAllOnesValue(InBits);
24787     Mask = Mask.zext(VT.getScalarSizeInBits());
24788     return DAG.getNode(ISD::AND, DL, VT,
24789                        Op, DAG.getConstant(Mask, DL, VT));
24790   }
24791   case ISD::SIGN_EXTEND:
24792     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24793                        Op, DAG.getValueType(NarrowVT));
24794   default:
24795     llvm_unreachable("Unexpected opcode");
24796   }
24797 }
24798
24799 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24800                                  TargetLowering::DAGCombinerInfo &DCI,
24801                                  const X86Subtarget *Subtarget) {
24802   SDValue N0 = N->getOperand(0);
24803   SDValue N1 = N->getOperand(1);
24804   SDLoc DL(N);
24805
24806   // A vector zext_in_reg may be represented as a shuffle,
24807   // feeding into a bitcast (this represents anyext) feeding into
24808   // an and with a mask.
24809   // We'd like to try to combine that into a shuffle with zero
24810   // plus a bitcast, removing the and.
24811   if (N0.getOpcode() != ISD::BITCAST ||
24812       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24813     return SDValue();
24814
24815   // The other side of the AND should be a splat of 2^C, where C
24816   // is the number of bits in the source type.
24817   if (N1.getOpcode() == ISD::BITCAST)
24818     N1 = N1.getOperand(0);
24819   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24820     return SDValue();
24821   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24822
24823   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24824   EVT SrcType = Shuffle->getValueType(0);
24825
24826   // We expect a single-source shuffle
24827   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24828     return SDValue();
24829
24830   unsigned SrcSize = SrcType.getScalarSizeInBits();
24831
24832   APInt SplatValue, SplatUndef;
24833   unsigned SplatBitSize;
24834   bool HasAnyUndefs;
24835   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24836                                 SplatBitSize, HasAnyUndefs))
24837     return SDValue();
24838
24839   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24840   // Make sure the splat matches the mask we expect
24841   if (SplatBitSize > ResSize ||
24842       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24843     return SDValue();
24844
24845   // Make sure the input and output size make sense
24846   if (SrcSize >= ResSize || ResSize % SrcSize)
24847     return SDValue();
24848
24849   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24850   // The number of u's between each two values depends on the ratio between
24851   // the source and dest type.
24852   unsigned ZextRatio = ResSize / SrcSize;
24853   bool IsZext = true;
24854   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24855     if (i % ZextRatio) {
24856       if (Shuffle->getMaskElt(i) > 0) {
24857         // Expected undef
24858         IsZext = false;
24859         break;
24860       }
24861     } else {
24862       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24863         // Expected element number
24864         IsZext = false;
24865         break;
24866       }
24867     }
24868   }
24869
24870   if (!IsZext)
24871     return SDValue();
24872
24873   // Ok, perform the transformation - replace the shuffle with
24874   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24875   // (instead of undef) where the k elements come from the zero vector.
24876   SmallVector<int, 8> Mask;
24877   unsigned NumElems = SrcType.getVectorNumElements();
24878   for (unsigned i = 0; i < NumElems; ++i)
24879     if (i % ZextRatio)
24880       Mask.push_back(NumElems);
24881     else
24882       Mask.push_back(i / ZextRatio);
24883
24884   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24885     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24886   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24887 }
24888
24889 /// If both input operands of a logic op are being cast from floating point
24890 /// types, try to convert this into a floating point logic node to avoid
24891 /// unnecessary moves from SSE to integer registers.
24892 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24893                                         const X86Subtarget *Subtarget) {
24894   unsigned FPOpcode = ISD::DELETED_NODE;
24895   if (N->getOpcode() == ISD::AND)
24896     FPOpcode = X86ISD::FAND;
24897   else if (N->getOpcode() == ISD::OR)
24898     FPOpcode = X86ISD::FOR;
24899   else if (N->getOpcode() == ISD::XOR)
24900     FPOpcode = X86ISD::FXOR;
24901
24902   assert(FPOpcode != ISD::DELETED_NODE &&
24903          "Unexpected input node for FP logic conversion");
24904
24905   EVT VT = N->getValueType(0);
24906   SDValue N0 = N->getOperand(0);
24907   SDValue N1 = N->getOperand(1);
24908   SDLoc DL(N);
24909   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24910       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24911        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24912     SDValue N00 = N0.getOperand(0);
24913     SDValue N10 = N1.getOperand(0);
24914     EVT N00Type = N00.getValueType();
24915     EVT N10Type = N10.getValueType();
24916     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24917       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24918       return DAG.getBitcast(VT, FPLogic);
24919     }
24920   }
24921   return SDValue();
24922 }
24923
24924 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24925                                  TargetLowering::DAGCombinerInfo &DCI,
24926                                  const X86Subtarget *Subtarget) {
24927   if (DCI.isBeforeLegalizeOps())
24928     return SDValue();
24929
24930   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24931     return Zext;
24932
24933   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24934     return R;
24935
24936   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24937     return FPLogic;
24938
24939   EVT VT = N->getValueType(0);
24940   SDValue N0 = N->getOperand(0);
24941   SDValue N1 = N->getOperand(1);
24942   SDLoc DL(N);
24943
24944   // Create BEXTR instructions
24945   // BEXTR is ((X >> imm) & (2**size-1))
24946   if (VT == MVT::i32 || VT == MVT::i64) {
24947     // Check for BEXTR.
24948     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24949         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24950       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24951       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24952       if (MaskNode && ShiftNode) {
24953         uint64_t Mask = MaskNode->getZExtValue();
24954         uint64_t Shift = ShiftNode->getZExtValue();
24955         if (isMask_64(Mask)) {
24956           uint64_t MaskSize = countPopulation(Mask);
24957           if (Shift + MaskSize <= VT.getSizeInBits())
24958             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24959                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24960                                                VT));
24961         }
24962       }
24963     } // BEXTR
24964
24965     return SDValue();
24966   }
24967
24968   // Want to form ANDNP nodes:
24969   // 1) In the hopes of then easily combining them with OR and AND nodes
24970   //    to form PBLEND/PSIGN.
24971   // 2) To match ANDN packed intrinsics
24972   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24973     return SDValue();
24974
24975   // Check LHS for vnot
24976   if (N0.getOpcode() == ISD::XOR &&
24977       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24978       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24979     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24980
24981   // Check RHS for vnot
24982   if (N1.getOpcode() == ISD::XOR &&
24983       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24984       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24985     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24986
24987   return SDValue();
24988 }
24989
24990 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24991                                 TargetLowering::DAGCombinerInfo &DCI,
24992                                 const X86Subtarget *Subtarget) {
24993   if (DCI.isBeforeLegalizeOps())
24994     return SDValue();
24995
24996   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24997     return R;
24998
24999   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25000     return FPLogic;
25001
25002   SDValue N0 = N->getOperand(0);
25003   SDValue N1 = N->getOperand(1);
25004   EVT VT = N->getValueType(0);
25005
25006   // look for psign/blend
25007   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25008     if (!Subtarget->hasSSSE3() ||
25009         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25010       return SDValue();
25011
25012     // Canonicalize pandn to RHS
25013     if (N0.getOpcode() == X86ISD::ANDNP)
25014       std::swap(N0, N1);
25015     // or (and (m, y), (pandn m, x))
25016     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25017       SDValue Mask = N1.getOperand(0);
25018       SDValue X    = N1.getOperand(1);
25019       SDValue Y;
25020       if (N0.getOperand(0) == Mask)
25021         Y = N0.getOperand(1);
25022       if (N0.getOperand(1) == Mask)
25023         Y = N0.getOperand(0);
25024
25025       // Check to see if the mask appeared in both the AND and ANDNP and
25026       if (!Y.getNode())
25027         return SDValue();
25028
25029       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25030       // Look through mask bitcast.
25031       if (Mask.getOpcode() == ISD::BITCAST)
25032         Mask = Mask.getOperand(0);
25033       if (X.getOpcode() == ISD::BITCAST)
25034         X = X.getOperand(0);
25035       if (Y.getOpcode() == ISD::BITCAST)
25036         Y = Y.getOperand(0);
25037
25038       EVT MaskVT = Mask.getValueType();
25039
25040       // Validate that the Mask operand is a vector sra node.
25041       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25042       // there is no psrai.b
25043       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25044       unsigned SraAmt = ~0;
25045       if (Mask.getOpcode() == ISD::SRA) {
25046         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25047           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25048             SraAmt = AmtConst->getZExtValue();
25049       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25050         SDValue SraC = Mask.getOperand(1);
25051         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25052       }
25053       if ((SraAmt + 1) != EltBits)
25054         return SDValue();
25055
25056       SDLoc DL(N);
25057
25058       // Now we know we at least have a plendvb with the mask val.  See if
25059       // we can form a psignb/w/d.
25060       // psign = x.type == y.type == mask.type && y = sub(0, x);
25061       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25062           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25063           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25064         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25065                "Unsupported VT for PSIGN");
25066         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25067         return DAG.getBitcast(VT, Mask);
25068       }
25069       // PBLENDVB only available on SSE 4.1
25070       if (!Subtarget->hasSSE41())
25071         return SDValue();
25072
25073       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25074
25075       X = DAG.getBitcast(BlendVT, X);
25076       Y = DAG.getBitcast(BlendVT, Y);
25077       Mask = DAG.getBitcast(BlendVT, Mask);
25078       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25079       return DAG.getBitcast(VT, Mask);
25080     }
25081   }
25082
25083   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25084     return SDValue();
25085
25086   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25087   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25088
25089   // SHLD/SHRD instructions have lower register pressure, but on some
25090   // platforms they have higher latency than the equivalent
25091   // series of shifts/or that would otherwise be generated.
25092   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25093   // have higher latencies and we are not optimizing for size.
25094   if (!OptForSize && Subtarget->isSHLDSlow())
25095     return SDValue();
25096
25097   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25098     std::swap(N0, N1);
25099   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25100     return SDValue();
25101   if (!N0.hasOneUse() || !N1.hasOneUse())
25102     return SDValue();
25103
25104   SDValue ShAmt0 = N0.getOperand(1);
25105   if (ShAmt0.getValueType() != MVT::i8)
25106     return SDValue();
25107   SDValue ShAmt1 = N1.getOperand(1);
25108   if (ShAmt1.getValueType() != MVT::i8)
25109     return SDValue();
25110   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25111     ShAmt0 = ShAmt0.getOperand(0);
25112   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25113     ShAmt1 = ShAmt1.getOperand(0);
25114
25115   SDLoc DL(N);
25116   unsigned Opc = X86ISD::SHLD;
25117   SDValue Op0 = N0.getOperand(0);
25118   SDValue Op1 = N1.getOperand(0);
25119   if (ShAmt0.getOpcode() == ISD::SUB) {
25120     Opc = X86ISD::SHRD;
25121     std::swap(Op0, Op1);
25122     std::swap(ShAmt0, ShAmt1);
25123   }
25124
25125   unsigned Bits = VT.getSizeInBits();
25126   if (ShAmt1.getOpcode() == ISD::SUB) {
25127     SDValue Sum = ShAmt1.getOperand(0);
25128     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25129       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25130       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25131         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25132       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25133         return DAG.getNode(Opc, DL, VT,
25134                            Op0, Op1,
25135                            DAG.getNode(ISD::TRUNCATE, DL,
25136                                        MVT::i8, ShAmt0));
25137     }
25138   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25139     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25140     if (ShAmt0C &&
25141         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25142       return DAG.getNode(Opc, DL, VT,
25143                          N0.getOperand(0), N1.getOperand(0),
25144                          DAG.getNode(ISD::TRUNCATE, DL,
25145                                        MVT::i8, ShAmt0));
25146   }
25147
25148   return SDValue();
25149 }
25150
25151 // Generate NEG and CMOV for integer abs.
25152 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25153   EVT VT = N->getValueType(0);
25154
25155   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25156   // 8-bit integer abs to NEG and CMOV.
25157   if (VT.isInteger() && VT.getSizeInBits() == 8)
25158     return SDValue();
25159
25160   SDValue N0 = N->getOperand(0);
25161   SDValue N1 = N->getOperand(1);
25162   SDLoc DL(N);
25163
25164   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25165   // and change it to SUB and CMOV.
25166   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25167       N0.getOpcode() == ISD::ADD &&
25168       N0.getOperand(1) == N1 &&
25169       N1.getOpcode() == ISD::SRA &&
25170       N1.getOperand(0) == N0.getOperand(0))
25171     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25172       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25173         // Generate SUB & CMOV.
25174         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25175                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25176
25177         SDValue Ops[] = { N0.getOperand(0), Neg,
25178                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25179                           SDValue(Neg.getNode(), 1) };
25180         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25181       }
25182   return SDValue();
25183 }
25184
25185 // Try to turn tests against the signbit in the form of:
25186 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25187 // into:
25188 //   SETGT(X, -1)
25189 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25190   // This is only worth doing if the output type is i8.
25191   if (N->getValueType(0) != MVT::i8)
25192     return SDValue();
25193
25194   SDValue N0 = N->getOperand(0);
25195   SDValue N1 = N->getOperand(1);
25196
25197   // We should be performing an xor against a truncated shift.
25198   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25199     return SDValue();
25200
25201   // Make sure we are performing an xor against one.
25202   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25203     return SDValue();
25204
25205   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25206   SDValue Shift = N0.getOperand(0);
25207   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25208     return SDValue();
25209
25210   // Make sure we are truncating from one of i16, i32 or i64.
25211   EVT ShiftTy = Shift.getValueType();
25212   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25213     return SDValue();
25214
25215   // Make sure the shift amount extracts the sign bit.
25216   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25217       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25218     return SDValue();
25219
25220   // Create a greater-than comparison against -1.
25221   // N.B. Using SETGE against 0 works but we want a canonical looking
25222   // comparison, using SETGT matches up with what TranslateX86CC.
25223   SDLoc DL(N);
25224   SDValue ShiftOp = Shift.getOperand(0);
25225   EVT ShiftOpTy = ShiftOp.getValueType();
25226   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25227                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25228   return Cond;
25229 }
25230
25231 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25232                                  TargetLowering::DAGCombinerInfo &DCI,
25233                                  const X86Subtarget *Subtarget) {
25234   if (DCI.isBeforeLegalizeOps())
25235     return SDValue();
25236
25237   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25238     return RV;
25239
25240   if (Subtarget->hasCMov())
25241     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25242       return RV;
25243
25244   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25245     return FPLogic;
25246
25247   return SDValue();
25248 }
25249
25250 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25251 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25252                                   TargetLowering::DAGCombinerInfo &DCI,
25253                                   const X86Subtarget *Subtarget) {
25254   LoadSDNode *Ld = cast<LoadSDNode>(N);
25255   EVT RegVT = Ld->getValueType(0);
25256   EVT MemVT = Ld->getMemoryVT();
25257   SDLoc dl(Ld);
25258   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25259
25260   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25261   // into two 16-byte operations.
25262   ISD::LoadExtType Ext = Ld->getExtensionType();
25263   bool Fast;
25264   unsigned AddressSpace = Ld->getAddressSpace();
25265   unsigned Alignment = Ld->getAlignment();
25266   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25267       Ext == ISD::NON_EXTLOAD &&
25268       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25269                              AddressSpace, Alignment, &Fast) && !Fast) {
25270     unsigned NumElems = RegVT.getVectorNumElements();
25271     if (NumElems < 2)
25272       return SDValue();
25273
25274     SDValue Ptr = Ld->getBasePtr();
25275     SDValue Increment =
25276         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25277
25278     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25279                                   NumElems/2);
25280     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25281                                 Ld->getPointerInfo(), Ld->isVolatile(),
25282                                 Ld->isNonTemporal(), Ld->isInvariant(),
25283                                 Alignment);
25284     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25285     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25286                                 Ld->getPointerInfo(), Ld->isVolatile(),
25287                                 Ld->isNonTemporal(), Ld->isInvariant(),
25288                                 std::min(16U, Alignment));
25289     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25290                              Load1.getValue(1),
25291                              Load2.getValue(1));
25292
25293     SDValue NewVec = DAG.getUNDEF(RegVT);
25294     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25295     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25296     return DCI.CombineTo(N, NewVec, TF, true);
25297   }
25298
25299   return SDValue();
25300 }
25301
25302 /// PerformMLOADCombine - Resolve extending loads
25303 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25304                                    TargetLowering::DAGCombinerInfo &DCI,
25305                                    const X86Subtarget *Subtarget) {
25306   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25307   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25308     return SDValue();
25309
25310   EVT VT = Mld->getValueType(0);
25311   unsigned NumElems = VT.getVectorNumElements();
25312   EVT LdVT = Mld->getMemoryVT();
25313   SDLoc dl(Mld);
25314
25315   assert(LdVT != VT && "Cannot extend to the same type");
25316   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25317   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25318   // From, To sizes and ElemCount must be pow of two
25319   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25320     "Unexpected size for extending masked load");
25321
25322   unsigned SizeRatio  = ToSz / FromSz;
25323   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25324
25325   // Create a type on which we perform the shuffle
25326   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25327           LdVT.getScalarType(), NumElems*SizeRatio);
25328   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25329
25330   // Convert Src0 value
25331   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25332   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25333     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25334     for (unsigned i = 0; i != NumElems; ++i)
25335       ShuffleVec[i] = i * SizeRatio;
25336
25337     // Can't shuffle using an illegal type.
25338     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25339            "WideVecVT should be legal");
25340     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25341                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25342   }
25343   // Prepare the new mask
25344   SDValue NewMask;
25345   SDValue Mask = Mld->getMask();
25346   if (Mask.getValueType() == VT) {
25347     // Mask and original value have the same type
25348     NewMask = DAG.getBitcast(WideVecVT, Mask);
25349     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25350     for (unsigned i = 0; i != NumElems; ++i)
25351       ShuffleVec[i] = i * SizeRatio;
25352     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25353       ShuffleVec[i] = NumElems*SizeRatio;
25354     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25355                                    DAG.getConstant(0, dl, WideVecVT),
25356                                    &ShuffleVec[0]);
25357   }
25358   else {
25359     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25360     unsigned WidenNumElts = NumElems*SizeRatio;
25361     unsigned MaskNumElts = VT.getVectorNumElements();
25362     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25363                                      WidenNumElts);
25364
25365     unsigned NumConcat = WidenNumElts / MaskNumElts;
25366     SmallVector<SDValue, 16> Ops(NumConcat);
25367     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25368     Ops[0] = Mask;
25369     for (unsigned i = 1; i != NumConcat; ++i)
25370       Ops[i] = ZeroVal;
25371
25372     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25373   }
25374
25375   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25376                                      Mld->getBasePtr(), NewMask, WideSrc0,
25377                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25378                                      ISD::NON_EXTLOAD);
25379   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25380   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25381 }
25382 /// PerformMSTORECombine - Resolve truncating stores
25383 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25384                                     const X86Subtarget *Subtarget) {
25385   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25386   if (!Mst->isTruncatingStore())
25387     return SDValue();
25388
25389   EVT VT = Mst->getValue().getValueType();
25390   unsigned NumElems = VT.getVectorNumElements();
25391   EVT StVT = Mst->getMemoryVT();
25392   SDLoc dl(Mst);
25393
25394   assert(StVT != VT && "Cannot truncate to the same type");
25395   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25396   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25397
25398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25399
25400   // The truncating store is legal in some cases. For example
25401   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25402   // are designated for truncate store.
25403   // In this case we don't need any further transformations.
25404   if (TLI.isTruncStoreLegal(VT, StVT))
25405     return SDValue();
25406
25407   // From, To sizes and ElemCount must be pow of two
25408   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25409     "Unexpected size for truncating masked store");
25410   // We are going to use the original vector elt for storing.
25411   // Accumulated smaller vector elements must be a multiple of the store size.
25412   assert (((NumElems * FromSz) % ToSz) == 0 &&
25413           "Unexpected ratio for truncating masked store");
25414
25415   unsigned SizeRatio  = FromSz / ToSz;
25416   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25417
25418   // Create a type on which we perform the shuffle
25419   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25420           StVT.getScalarType(), NumElems*SizeRatio);
25421
25422   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25423
25424   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25425   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25426   for (unsigned i = 0; i != NumElems; ++i)
25427     ShuffleVec[i] = i * SizeRatio;
25428
25429   // Can't shuffle using an illegal type.
25430   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25431          "WideVecVT should be legal");
25432
25433   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25434                                         DAG.getUNDEF(WideVecVT),
25435                                         &ShuffleVec[0]);
25436
25437   SDValue NewMask;
25438   SDValue Mask = Mst->getMask();
25439   if (Mask.getValueType() == VT) {
25440     // Mask and original value have the same type
25441     NewMask = DAG.getBitcast(WideVecVT, Mask);
25442     for (unsigned i = 0; i != NumElems; ++i)
25443       ShuffleVec[i] = i * SizeRatio;
25444     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25445       ShuffleVec[i] = NumElems*SizeRatio;
25446     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25447                                    DAG.getConstant(0, dl, WideVecVT),
25448                                    &ShuffleVec[0]);
25449   }
25450   else {
25451     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25452     unsigned WidenNumElts = NumElems*SizeRatio;
25453     unsigned MaskNumElts = VT.getVectorNumElements();
25454     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25455                                      WidenNumElts);
25456
25457     unsigned NumConcat = WidenNumElts / MaskNumElts;
25458     SmallVector<SDValue, 16> Ops(NumConcat);
25459     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25460     Ops[0] = Mask;
25461     for (unsigned i = 1; i != NumConcat; ++i)
25462       Ops[i] = ZeroVal;
25463
25464     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25465   }
25466
25467   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25468                             NewMask, StVT, Mst->getMemOperand(), false);
25469 }
25470 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25471 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25472                                    const X86Subtarget *Subtarget) {
25473   StoreSDNode *St = cast<StoreSDNode>(N);
25474   EVT VT = St->getValue().getValueType();
25475   EVT StVT = St->getMemoryVT();
25476   SDLoc dl(St);
25477   SDValue StoredVal = St->getOperand(1);
25478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25479
25480   // If we are saving a concatenation of two XMM registers and 32-byte stores
25481   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25482   bool Fast;
25483   unsigned AddressSpace = St->getAddressSpace();
25484   unsigned Alignment = St->getAlignment();
25485   if (VT.is256BitVector() && StVT == VT &&
25486       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25487                              AddressSpace, Alignment, &Fast) && !Fast) {
25488     unsigned NumElems = VT.getVectorNumElements();
25489     if (NumElems < 2)
25490       return SDValue();
25491
25492     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25493     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25494
25495     SDValue Stride =
25496         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25497     SDValue Ptr0 = St->getBasePtr();
25498     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25499
25500     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25501                                 St->getPointerInfo(), St->isVolatile(),
25502                                 St->isNonTemporal(), Alignment);
25503     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25504                                 St->getPointerInfo(), St->isVolatile(),
25505                                 St->isNonTemporal(),
25506                                 std::min(16U, Alignment));
25507     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25508   }
25509
25510   // Optimize trunc store (of multiple scalars) to shuffle and store.
25511   // First, pack all of the elements in one place. Next, store to memory
25512   // in fewer chunks.
25513   if (St->isTruncatingStore() && VT.isVector()) {
25514     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25515     unsigned NumElems = VT.getVectorNumElements();
25516     assert(StVT != VT && "Cannot truncate to the same type");
25517     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25518     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25519
25520     // The truncating store is legal in some cases. For example
25521     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25522     // are designated for truncate store.
25523     // In this case we don't need any further transformations.
25524     if (TLI.isTruncStoreLegal(VT, StVT))
25525       return SDValue();
25526
25527     // From, To sizes and ElemCount must be pow of two
25528     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25529     // We are going to use the original vector elt for storing.
25530     // Accumulated smaller vector elements must be a multiple of the store size.
25531     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25532
25533     unsigned SizeRatio  = FromSz / ToSz;
25534
25535     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25536
25537     // Create a type on which we perform the shuffle
25538     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25539             StVT.getScalarType(), NumElems*SizeRatio);
25540
25541     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25542
25543     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25544     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25545     for (unsigned i = 0; i != NumElems; ++i)
25546       ShuffleVec[i] = i * SizeRatio;
25547
25548     // Can't shuffle using an illegal type.
25549     if (!TLI.isTypeLegal(WideVecVT))
25550       return SDValue();
25551
25552     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25553                                          DAG.getUNDEF(WideVecVT),
25554                                          &ShuffleVec[0]);
25555     // At this point all of the data is stored at the bottom of the
25556     // register. We now need to save it to mem.
25557
25558     // Find the largest store unit
25559     MVT StoreType = MVT::i8;
25560     for (MVT Tp : MVT::integer_valuetypes()) {
25561       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25562         StoreType = Tp;
25563     }
25564
25565     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25566     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25567         (64 <= NumElems * ToSz))
25568       StoreType = MVT::f64;
25569
25570     // Bitcast the original vector into a vector of store-size units
25571     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25572             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25573     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25574     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25575     SmallVector<SDValue, 8> Chains;
25576     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25577                                         TLI.getPointerTy(DAG.getDataLayout()));
25578     SDValue Ptr = St->getBasePtr();
25579
25580     // Perform one or more big stores into memory.
25581     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25582       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25583                                    StoreType, ShuffWide,
25584                                    DAG.getIntPtrConstant(i, dl));
25585       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25586                                 St->getPointerInfo(), St->isVolatile(),
25587                                 St->isNonTemporal(), St->getAlignment());
25588       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25589       Chains.push_back(Ch);
25590     }
25591
25592     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25593   }
25594
25595   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25596   // the FP state in cases where an emms may be missing.
25597   // A preferable solution to the general problem is to figure out the right
25598   // places to insert EMMS.  This qualifies as a quick hack.
25599
25600   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25601   if (VT.getSizeInBits() != 64)
25602     return SDValue();
25603
25604   const Function *F = DAG.getMachineFunction().getFunction();
25605   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25606   bool F64IsLegal =
25607       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25608   if ((VT.isVector() ||
25609        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25610       isa<LoadSDNode>(St->getValue()) &&
25611       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25612       St->getChain().hasOneUse() && !St->isVolatile()) {
25613     SDNode* LdVal = St->getValue().getNode();
25614     LoadSDNode *Ld = nullptr;
25615     int TokenFactorIndex = -1;
25616     SmallVector<SDValue, 8> Ops;
25617     SDNode* ChainVal = St->getChain().getNode();
25618     // Must be a store of a load.  We currently handle two cases:  the load
25619     // is a direct child, and it's under an intervening TokenFactor.  It is
25620     // possible to dig deeper under nested TokenFactors.
25621     if (ChainVal == LdVal)
25622       Ld = cast<LoadSDNode>(St->getChain());
25623     else if (St->getValue().hasOneUse() &&
25624              ChainVal->getOpcode() == ISD::TokenFactor) {
25625       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25626         if (ChainVal->getOperand(i).getNode() == LdVal) {
25627           TokenFactorIndex = i;
25628           Ld = cast<LoadSDNode>(St->getValue());
25629         } else
25630           Ops.push_back(ChainVal->getOperand(i));
25631       }
25632     }
25633
25634     if (!Ld || !ISD::isNormalLoad(Ld))
25635       return SDValue();
25636
25637     // If this is not the MMX case, i.e. we are just turning i64 load/store
25638     // into f64 load/store, avoid the transformation if there are multiple
25639     // uses of the loaded value.
25640     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25641       return SDValue();
25642
25643     SDLoc LdDL(Ld);
25644     SDLoc StDL(N);
25645     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25646     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25647     // pair instead.
25648     if (Subtarget->is64Bit() || F64IsLegal) {
25649       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25650       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25651                                   Ld->getPointerInfo(), Ld->isVolatile(),
25652                                   Ld->isNonTemporal(), Ld->isInvariant(),
25653                                   Ld->getAlignment());
25654       SDValue NewChain = NewLd.getValue(1);
25655       if (TokenFactorIndex != -1) {
25656         Ops.push_back(NewChain);
25657         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25658       }
25659       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25660                           St->getPointerInfo(),
25661                           St->isVolatile(), St->isNonTemporal(),
25662                           St->getAlignment());
25663     }
25664
25665     // Otherwise, lower to two pairs of 32-bit loads / stores.
25666     SDValue LoAddr = Ld->getBasePtr();
25667     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25668                                  DAG.getConstant(4, LdDL, MVT::i32));
25669
25670     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25671                                Ld->getPointerInfo(),
25672                                Ld->isVolatile(), Ld->isNonTemporal(),
25673                                Ld->isInvariant(), Ld->getAlignment());
25674     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25675                                Ld->getPointerInfo().getWithOffset(4),
25676                                Ld->isVolatile(), Ld->isNonTemporal(),
25677                                Ld->isInvariant(),
25678                                MinAlign(Ld->getAlignment(), 4));
25679
25680     SDValue NewChain = LoLd.getValue(1);
25681     if (TokenFactorIndex != -1) {
25682       Ops.push_back(LoLd);
25683       Ops.push_back(HiLd);
25684       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25685     }
25686
25687     LoAddr = St->getBasePtr();
25688     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25689                          DAG.getConstant(4, StDL, MVT::i32));
25690
25691     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25692                                 St->getPointerInfo(),
25693                                 St->isVolatile(), St->isNonTemporal(),
25694                                 St->getAlignment());
25695     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25696                                 St->getPointerInfo().getWithOffset(4),
25697                                 St->isVolatile(),
25698                                 St->isNonTemporal(),
25699                                 MinAlign(St->getAlignment(), 4));
25700     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25701   }
25702
25703   // This is similar to the above case, but here we handle a scalar 64-bit
25704   // integer store that is extracted from a vector on a 32-bit target.
25705   // If we have SSE2, then we can treat it like a floating-point double
25706   // to get past legalization. The execution dependencies fixup pass will
25707   // choose the optimal machine instruction for the store if this really is
25708   // an integer or v2f32 rather than an f64.
25709   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25710       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25711     SDValue OldExtract = St->getOperand(1);
25712     SDValue ExtOp0 = OldExtract.getOperand(0);
25713     unsigned VecSize = ExtOp0.getValueSizeInBits();
25714     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25715     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25716     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25717                                      BitCast, OldExtract.getOperand(1));
25718     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25719                         St->getPointerInfo(), St->isVolatile(),
25720                         St->isNonTemporal(), St->getAlignment());
25721   }
25722
25723   return SDValue();
25724 }
25725
25726 /// Return 'true' if this vector operation is "horizontal"
25727 /// and return the operands for the horizontal operation in LHS and RHS.  A
25728 /// horizontal operation performs the binary operation on successive elements
25729 /// of its first operand, then on successive elements of its second operand,
25730 /// returning the resulting values in a vector.  For example, if
25731 ///   A = < float a0, float a1, float a2, float a3 >
25732 /// and
25733 ///   B = < float b0, float b1, float b2, float b3 >
25734 /// then the result of doing a horizontal operation on A and B is
25735 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25736 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25737 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25738 /// set to A, RHS to B, and the routine returns 'true'.
25739 /// Note that the binary operation should have the property that if one of the
25740 /// operands is UNDEF then the result is UNDEF.
25741 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25742   // Look for the following pattern: if
25743   //   A = < float a0, float a1, float a2, float a3 >
25744   //   B = < float b0, float b1, float b2, float b3 >
25745   // and
25746   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25747   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25748   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25749   // which is A horizontal-op B.
25750
25751   // At least one of the operands should be a vector shuffle.
25752   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25753       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25754     return false;
25755
25756   MVT VT = LHS.getSimpleValueType();
25757
25758   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25759          "Unsupported vector type for horizontal add/sub");
25760
25761   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25762   // operate independently on 128-bit lanes.
25763   unsigned NumElts = VT.getVectorNumElements();
25764   unsigned NumLanes = VT.getSizeInBits()/128;
25765   unsigned NumLaneElts = NumElts / NumLanes;
25766   assert((NumLaneElts % 2 == 0) &&
25767          "Vector type should have an even number of elements in each lane");
25768   unsigned HalfLaneElts = NumLaneElts/2;
25769
25770   // View LHS in the form
25771   //   LHS = VECTOR_SHUFFLE A, B, LMask
25772   // If LHS is not a shuffle then pretend it is the shuffle
25773   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25774   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25775   // type VT.
25776   SDValue A, B;
25777   SmallVector<int, 16> LMask(NumElts);
25778   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25779     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25780       A = LHS.getOperand(0);
25781     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25782       B = LHS.getOperand(1);
25783     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25784     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25785   } else {
25786     if (LHS.getOpcode() != ISD::UNDEF)
25787       A = LHS;
25788     for (unsigned i = 0; i != NumElts; ++i)
25789       LMask[i] = i;
25790   }
25791
25792   // Likewise, view RHS in the form
25793   //   RHS = VECTOR_SHUFFLE C, D, RMask
25794   SDValue C, D;
25795   SmallVector<int, 16> RMask(NumElts);
25796   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25797     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25798       C = RHS.getOperand(0);
25799     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25800       D = RHS.getOperand(1);
25801     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25802     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25803   } else {
25804     if (RHS.getOpcode() != ISD::UNDEF)
25805       C = RHS;
25806     for (unsigned i = 0; i != NumElts; ++i)
25807       RMask[i] = i;
25808   }
25809
25810   // Check that the shuffles are both shuffling the same vectors.
25811   if (!(A == C && B == D) && !(A == D && B == C))
25812     return false;
25813
25814   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25815   if (!A.getNode() && !B.getNode())
25816     return false;
25817
25818   // If A and B occur in reverse order in RHS, then "swap" them (which means
25819   // rewriting the mask).
25820   if (A != C)
25821     ShuffleVectorSDNode::commuteMask(RMask);
25822
25823   // At this point LHS and RHS are equivalent to
25824   //   LHS = VECTOR_SHUFFLE A, B, LMask
25825   //   RHS = VECTOR_SHUFFLE A, B, RMask
25826   // Check that the masks correspond to performing a horizontal operation.
25827   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25828     for (unsigned i = 0; i != NumLaneElts; ++i) {
25829       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25830
25831       // Ignore any UNDEF components.
25832       if (LIdx < 0 || RIdx < 0 ||
25833           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25834           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25835         continue;
25836
25837       // Check that successive elements are being operated on.  If not, this is
25838       // not a horizontal operation.
25839       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25840       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25841       if (!(LIdx == Index && RIdx == Index + 1) &&
25842           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25843         return false;
25844     }
25845   }
25846
25847   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25848   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25849   return true;
25850 }
25851
25852 /// Do target-specific dag combines on floating point adds.
25853 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25854                                   const X86Subtarget *Subtarget) {
25855   EVT VT = N->getValueType(0);
25856   SDValue LHS = N->getOperand(0);
25857   SDValue RHS = N->getOperand(1);
25858
25859   // Try to synthesize horizontal adds from adds of shuffles.
25860   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25861        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25862       isHorizontalBinOp(LHS, RHS, true))
25863     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25864   return SDValue();
25865 }
25866
25867 /// Do target-specific dag combines on floating point subs.
25868 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25869                                   const X86Subtarget *Subtarget) {
25870   EVT VT = N->getValueType(0);
25871   SDValue LHS = N->getOperand(0);
25872   SDValue RHS = N->getOperand(1);
25873
25874   // Try to synthesize horizontal subs from subs of shuffles.
25875   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25876        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25877       isHorizontalBinOp(LHS, RHS, false))
25878     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25879   return SDValue();
25880 }
25881
25882 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25883 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25884                                  const X86Subtarget *Subtarget) {
25885   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25886
25887   // F[X]OR(0.0, x) -> x
25888   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25889     if (C->getValueAPF().isPosZero())
25890       return N->getOperand(1);
25891
25892   // F[X]OR(x, 0.0) -> x
25893   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25894     if (C->getValueAPF().isPosZero())
25895       return N->getOperand(0);
25896
25897   EVT VT = N->getValueType(0);
25898   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25899     SDLoc dl(N);
25900     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25901     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25902
25903     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25904     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25905     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25906     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25907     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25908   }
25909   return SDValue();
25910 }
25911
25912 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25913 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25914   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25915
25916   // Only perform optimizations if UnsafeMath is used.
25917   if (!DAG.getTarget().Options.UnsafeFPMath)
25918     return SDValue();
25919
25920   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25921   // into FMINC and FMAXC, which are Commutative operations.
25922   unsigned NewOp = 0;
25923   switch (N->getOpcode()) {
25924     default: llvm_unreachable("unknown opcode");
25925     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25926     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25927   }
25928
25929   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25930                      N->getOperand(0), N->getOperand(1));
25931 }
25932
25933 /// Do target-specific dag combines on X86ISD::FAND nodes.
25934 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25935   // FAND(0.0, x) -> 0.0
25936   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25937     if (C->getValueAPF().isPosZero())
25938       return N->getOperand(0);
25939
25940   // FAND(x, 0.0) -> 0.0
25941   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25942     if (C->getValueAPF().isPosZero())
25943       return N->getOperand(1);
25944
25945   return SDValue();
25946 }
25947
25948 /// Do target-specific dag combines on X86ISD::FANDN nodes
25949 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25950   // FANDN(0.0, x) -> x
25951   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25952     if (C->getValueAPF().isPosZero())
25953       return N->getOperand(1);
25954
25955   // FANDN(x, 0.0) -> 0.0
25956   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25957     if (C->getValueAPF().isPosZero())
25958       return N->getOperand(1);
25959
25960   return SDValue();
25961 }
25962
25963 static SDValue PerformBTCombine(SDNode *N,
25964                                 SelectionDAG &DAG,
25965                                 TargetLowering::DAGCombinerInfo &DCI) {
25966   // BT ignores high bits in the bit index operand.
25967   SDValue Op1 = N->getOperand(1);
25968   if (Op1.hasOneUse()) {
25969     unsigned BitWidth = Op1.getValueSizeInBits();
25970     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25971     APInt KnownZero, KnownOne;
25972     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25973                                           !DCI.isBeforeLegalizeOps());
25974     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25975     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25976         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25977       DCI.CommitTargetLoweringOpt(TLO);
25978   }
25979   return SDValue();
25980 }
25981
25982 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25983   SDValue Op = N->getOperand(0);
25984   if (Op.getOpcode() == ISD::BITCAST)
25985     Op = Op.getOperand(0);
25986   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25987   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25988       VT.getVectorElementType().getSizeInBits() ==
25989       OpVT.getVectorElementType().getSizeInBits()) {
25990     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25991   }
25992   return SDValue();
25993 }
25994
25995 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25996                                                const X86Subtarget *Subtarget) {
25997   EVT VT = N->getValueType(0);
25998   if (!VT.isVector())
25999     return SDValue();
26000
26001   SDValue N0 = N->getOperand(0);
26002   SDValue N1 = N->getOperand(1);
26003   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
26004   SDLoc dl(N);
26005
26006   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
26007   // both SSE and AVX2 since there is no sign-extended shift right
26008   // operation on a vector with 64-bit elements.
26009   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
26010   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
26011   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
26012       N0.getOpcode() == ISD::SIGN_EXTEND)) {
26013     SDValue N00 = N0.getOperand(0);
26014
26015     // EXTLOAD has a better solution on AVX2,
26016     // it may be replaced with X86ISD::VSEXT node.
26017     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
26018       if (!ISD::isNormalLoad(N00.getNode()))
26019         return SDValue();
26020
26021     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
26022         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
26023                                   N00, N1);
26024       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
26025     }
26026   }
26027   return SDValue();
26028 }
26029
26030 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
26031 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
26032 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
26033 /// eliminate extend, add, and shift instructions.
26034 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
26035                                        const X86Subtarget *Subtarget) {
26036   // TODO: This should be valid for other integer types.
26037   EVT VT = Sext->getValueType(0);
26038   if (VT != MVT::i64)
26039     return SDValue();
26040
26041   // We need an 'add nsw' feeding into the 'sext'.
26042   SDValue Add = Sext->getOperand(0);
26043   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
26044     return SDValue();
26045
26046   // Having a constant operand to the 'add' ensures that we are not increasing
26047   // the instruction count because the constant is extended for free below.
26048   // A constant operand can also become the displacement field of an LEA.
26049   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
26050   if (!AddOp1)
26051     return SDValue();
26052
26053   // Don't make the 'add' bigger if there's no hope of combining it with some
26054   // other 'add' or 'shl' instruction.
26055   // TODO: It may be profitable to generate simpler LEA instructions in place
26056   // of single 'add' instructions, but the cost model for selecting an LEA
26057   // currently has a high threshold.
26058   bool HasLEAPotential = false;
26059   for (auto *User : Sext->uses()) {
26060     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
26061       HasLEAPotential = true;
26062       break;
26063     }
26064   }
26065   if (!HasLEAPotential)
26066     return SDValue();
26067
26068   // Everything looks good, so pull the 'sext' ahead of the 'add'.
26069   int64_t AddConstant = AddOp1->getSExtValue();
26070   SDValue AddOp0 = Add.getOperand(0);
26071   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
26072   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
26073
26074   // The wider add is guaranteed to not wrap because both operands are
26075   // sign-extended.
26076   SDNodeFlags Flags;
26077   Flags.setNoSignedWrap(true);
26078   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
26079 }
26080
26081 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
26082                                   TargetLowering::DAGCombinerInfo &DCI,
26083                                   const X86Subtarget *Subtarget) {
26084   SDValue N0 = N->getOperand(0);
26085   EVT VT = N->getValueType(0);
26086   EVT SVT = VT.getScalarType();
26087   EVT InVT = N0.getValueType();
26088   EVT InSVT = InVT.getScalarType();
26089   SDLoc DL(N);
26090
26091   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
26092   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
26093   // This exposes the sext to the sdivrem lowering, so that it directly extends
26094   // from AH (which we otherwise need to do contortions to access).
26095   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
26096       InVT == MVT::i8 && VT == MVT::i32) {
26097     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26098     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
26099                             N0.getOperand(0), N0.getOperand(1));
26100     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26101     return R.getValue(1);
26102   }
26103
26104   if (!DCI.isBeforeLegalizeOps()) {
26105     if (InVT == MVT::i1) {
26106       SDValue Zero = DAG.getConstant(0, DL, VT);
26107       SDValue AllOnes =
26108         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
26109       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
26110     }
26111     return SDValue();
26112   }
26113
26114   if (VT.isVector() && Subtarget->hasSSE2()) {
26115     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
26116       EVT InVT = N.getValueType();
26117       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
26118                                    Size / InVT.getScalarSizeInBits());
26119       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
26120                                     DAG.getUNDEF(InVT));
26121       Opnds[0] = N;
26122       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
26123     };
26124
26125     // If target-size is less than 128-bits, extend to a type that would extend
26126     // to 128 bits, extend that and extract the original target vector.
26127     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
26128         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26129         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26130       unsigned Scale = 128 / VT.getSizeInBits();
26131       EVT ExVT =
26132           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
26133       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
26134       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
26135       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
26136                          DAG.getIntPtrConstant(0, DL));
26137     }
26138
26139     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
26140     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
26141     if (VT.getSizeInBits() == 128 &&
26142         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26143         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26144       SDValue ExOp = ExtendVecSize(DL, N0, 128);
26145       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
26146     }
26147
26148     // On pre-AVX2 targets, split into 128-bit nodes of
26149     // ISD::SIGN_EXTEND_VECTOR_INREG.
26150     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
26151         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26152         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26153       unsigned NumVecs = VT.getSizeInBits() / 128;
26154       unsigned NumSubElts = 128 / SVT.getSizeInBits();
26155       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
26156       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
26157
26158       SmallVector<SDValue, 8> Opnds;
26159       for (unsigned i = 0, Offset = 0; i != NumVecs;
26160            ++i, Offset += NumSubElts) {
26161         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
26162                                      DAG.getIntPtrConstant(Offset, DL));
26163         SrcVec = ExtendVecSize(DL, SrcVec, 128);
26164         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26165         Opnds.push_back(SrcVec);
26166       }
26167       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26168     }
26169   }
26170
26171   if (Subtarget->hasAVX() && VT.is256BitVector())
26172     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26173       return R;
26174
26175   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26176     return NewAdd;
26177
26178   return SDValue();
26179 }
26180
26181 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26182                                  const X86Subtarget* Subtarget) {
26183   SDLoc dl(N);
26184   EVT VT = N->getValueType(0);
26185
26186   // Let legalize expand this if it isn't a legal type yet.
26187   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26188     return SDValue();
26189
26190   EVT ScalarVT = VT.getScalarType();
26191   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26192       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26193        !Subtarget->hasAVX512()))
26194     return SDValue();
26195
26196   SDValue A = N->getOperand(0);
26197   SDValue B = N->getOperand(1);
26198   SDValue C = N->getOperand(2);
26199
26200   bool NegA = (A.getOpcode() == ISD::FNEG);
26201   bool NegB = (B.getOpcode() == ISD::FNEG);
26202   bool NegC = (C.getOpcode() == ISD::FNEG);
26203
26204   // Negative multiplication when NegA xor NegB
26205   bool NegMul = (NegA != NegB);
26206   if (NegA)
26207     A = A.getOperand(0);
26208   if (NegB)
26209     B = B.getOperand(0);
26210   if (NegC)
26211     C = C.getOperand(0);
26212
26213   unsigned Opcode;
26214   if (!NegMul)
26215     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26216   else
26217     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26218
26219   return DAG.getNode(Opcode, dl, VT, A, B, C);
26220 }
26221
26222 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26223                                   TargetLowering::DAGCombinerInfo &DCI,
26224                                   const X86Subtarget *Subtarget) {
26225   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
26226   //           (and (i32 x86isd::setcc_carry), 1)
26227   // This eliminates the zext. This transformation is necessary because
26228   // ISD::SETCC is always legalized to i8.
26229   SDLoc dl(N);
26230   SDValue N0 = N->getOperand(0);
26231   EVT VT = N->getValueType(0);
26232
26233   if (N0.getOpcode() == ISD::AND &&
26234       N0.hasOneUse() &&
26235       N0.getOperand(0).hasOneUse()) {
26236     SDValue N00 = N0.getOperand(0);
26237     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26238       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26239       if (!C || C->getZExtValue() != 1)
26240         return SDValue();
26241       return DAG.getNode(ISD::AND, dl, VT,
26242                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26243                                      N00.getOperand(0), N00.getOperand(1)),
26244                          DAG.getConstant(1, dl, VT));
26245     }
26246   }
26247
26248   if (N0.getOpcode() == ISD::TRUNCATE &&
26249       N0.hasOneUse() &&
26250       N0.getOperand(0).hasOneUse()) {
26251     SDValue N00 = N0.getOperand(0);
26252     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26253       return DAG.getNode(ISD::AND, dl, VT,
26254                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26255                                      N00.getOperand(0), N00.getOperand(1)),
26256                          DAG.getConstant(1, dl, VT));
26257     }
26258   }
26259
26260   if (VT.is256BitVector())
26261     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26262       return R;
26263
26264   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26265   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26266   // This exposes the zext to the udivrem lowering, so that it directly extends
26267   // from AH (which we otherwise need to do contortions to access).
26268   if (N0.getOpcode() == ISD::UDIVREM &&
26269       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26270       (VT == MVT::i32 || VT == MVT::i64)) {
26271     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26272     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26273                             N0.getOperand(0), N0.getOperand(1));
26274     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26275     return R.getValue(1);
26276   }
26277
26278   return SDValue();
26279 }
26280
26281 // Optimize x == -y --> x+y == 0
26282 //          x != -y --> x+y != 0
26283 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26284                                       const X86Subtarget* Subtarget) {
26285   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26286   SDValue LHS = N->getOperand(0);
26287   SDValue RHS = N->getOperand(1);
26288   EVT VT = N->getValueType(0);
26289   SDLoc DL(N);
26290
26291   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26292     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26293       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26294         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26295                                    LHS.getOperand(1));
26296         return DAG.getSetCC(DL, N->getValueType(0), addV,
26297                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26298       }
26299   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26300     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26301       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26302         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26303                                    RHS.getOperand(1));
26304         return DAG.getSetCC(DL, N->getValueType(0), addV,
26305                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26306       }
26307
26308   if (VT.getScalarType() == MVT::i1 &&
26309       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26310     bool IsSEXT0 =
26311         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26312         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26313     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26314
26315     if (!IsSEXT0 || !IsVZero1) {
26316       // Swap the operands and update the condition code.
26317       std::swap(LHS, RHS);
26318       CC = ISD::getSetCCSwappedOperands(CC);
26319
26320       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26321                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26322       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26323     }
26324
26325     if (IsSEXT0 && IsVZero1) {
26326       assert(VT == LHS.getOperand(0).getValueType() &&
26327              "Uexpected operand type");
26328       if (CC == ISD::SETGT)
26329         return DAG.getConstant(0, DL, VT);
26330       if (CC == ISD::SETLE)
26331         return DAG.getConstant(1, DL, VT);
26332       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26333         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26334
26335       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26336              "Unexpected condition code!");
26337       return LHS.getOperand(0);
26338     }
26339   }
26340
26341   return SDValue();
26342 }
26343
26344 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26345   SDValue V0 = N->getOperand(0);
26346   SDValue V1 = N->getOperand(1);
26347   SDLoc DL(N);
26348   EVT VT = N->getValueType(0);
26349
26350   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26351   // operands and changing the mask to 1. This saves us a bunch of
26352   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26353   // x86InstrInfo knows how to commute this back after instruction selection
26354   // if it would help register allocation.
26355
26356   // TODO: If optimizing for size or a processor that doesn't suffer from
26357   // partial register update stalls, this should be transformed into a MOVSD
26358   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26359
26360   if (VT == MVT::v2f64)
26361     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26362       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26363         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26364         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26365       }
26366
26367   return SDValue();
26368 }
26369
26370 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26371 // as "sbb reg,reg", since it can be extended without zext and produces
26372 // an all-ones bit which is more useful than 0/1 in some cases.
26373 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26374                                MVT VT) {
26375   if (VT == MVT::i8)
26376     return DAG.getNode(ISD::AND, DL, VT,
26377                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26378                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26379                                    EFLAGS),
26380                        DAG.getConstant(1, DL, VT));
26381   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26382   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26383                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26384                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26385                                  EFLAGS));
26386 }
26387
26388 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26389 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26390                                    TargetLowering::DAGCombinerInfo &DCI,
26391                                    const X86Subtarget *Subtarget) {
26392   SDLoc DL(N);
26393   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26394   SDValue EFLAGS = N->getOperand(1);
26395
26396   if (CC == X86::COND_A) {
26397     // Try to convert COND_A into COND_B in an attempt to facilitate
26398     // materializing "setb reg".
26399     //
26400     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26401     // cannot take an immediate as its first operand.
26402     //
26403     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26404         EFLAGS.getValueType().isInteger() &&
26405         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26406       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26407                                    EFLAGS.getNode()->getVTList(),
26408                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26409       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26410       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26411     }
26412   }
26413
26414   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26415   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26416   // cases.
26417   if (CC == X86::COND_B)
26418     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26419
26420   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26421     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26422     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26423   }
26424
26425   return SDValue();
26426 }
26427
26428 // Optimize branch condition evaluation.
26429 //
26430 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26431                                     TargetLowering::DAGCombinerInfo &DCI,
26432                                     const X86Subtarget *Subtarget) {
26433   SDLoc DL(N);
26434   SDValue Chain = N->getOperand(0);
26435   SDValue Dest = N->getOperand(1);
26436   SDValue EFLAGS = N->getOperand(3);
26437   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26438
26439   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26440     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26441     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26442                        Flags);
26443   }
26444
26445   return SDValue();
26446 }
26447
26448 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26449                                                          SelectionDAG &DAG) {
26450   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26451   // optimize away operation when it's from a constant.
26452   //
26453   // The general transformation is:
26454   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26455   //       AND(VECTOR_CMP(x,y), constant2)
26456   //    constant2 = UNARYOP(constant)
26457
26458   // Early exit if this isn't a vector operation, the operand of the
26459   // unary operation isn't a bitwise AND, or if the sizes of the operations
26460   // aren't the same.
26461   EVT VT = N->getValueType(0);
26462   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26463       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26464       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26465     return SDValue();
26466
26467   // Now check that the other operand of the AND is a constant. We could
26468   // make the transformation for non-constant splats as well, but it's unclear
26469   // that would be a benefit as it would not eliminate any operations, just
26470   // perform one more step in scalar code before moving to the vector unit.
26471   if (BuildVectorSDNode *BV =
26472           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26473     // Bail out if the vector isn't a constant.
26474     if (!BV->isConstant())
26475       return SDValue();
26476
26477     // Everything checks out. Build up the new and improved node.
26478     SDLoc DL(N);
26479     EVT IntVT = BV->getValueType(0);
26480     // Create a new constant of the appropriate type for the transformed
26481     // DAG.
26482     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26483     // The AND node needs bitcasts to/from an integer vector type around it.
26484     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26485     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26486                                  N->getOperand(0)->getOperand(0), MaskConst);
26487     SDValue Res = DAG.getBitcast(VT, NewAnd);
26488     return Res;
26489   }
26490
26491   return SDValue();
26492 }
26493
26494 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26495                                         const X86Subtarget *Subtarget) {
26496   SDValue Op0 = N->getOperand(0);
26497   EVT VT = N->getValueType(0);
26498   EVT InVT = Op0.getValueType();
26499   EVT InSVT = InVT.getScalarType();
26500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26501
26502   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26503   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26504   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26505     SDLoc dl(N);
26506     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26507                                  InVT.getVectorNumElements());
26508     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26509
26510     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26511       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26512
26513     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26514   }
26515
26516   return SDValue();
26517 }
26518
26519 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26520                                         const X86Subtarget *Subtarget) {
26521   // First try to optimize away the conversion entirely when it's
26522   // conditionally from a constant. Vectors only.
26523   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26524     return Res;
26525
26526   // Now move on to more general possibilities.
26527   SDValue Op0 = N->getOperand(0);
26528   EVT VT = N->getValueType(0);
26529   EVT InVT = Op0.getValueType();
26530   EVT InSVT = InVT.getScalarType();
26531
26532   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26533   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26534   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26535     SDLoc dl(N);
26536     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26537                                  InVT.getVectorNumElements());
26538     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26539     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26540   }
26541
26542   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26543   // a 32-bit target where SSE doesn't support i64->FP operations.
26544   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
26545     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26546     EVT LdVT = Ld->getValueType(0);
26547
26548     // This transformation is not supported if the result type is f16
26549     if (VT == MVT::f16)
26550       return SDValue();
26551
26552     if (!Ld->isVolatile() && !VT.isVector() &&
26553         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26554         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26555       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26556           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26557       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26558       return FILDChain;
26559     }
26560   }
26561   return SDValue();
26562 }
26563
26564 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26565 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26566                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26567   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26568   // the result is either zero or one (depending on the input carry bit).
26569   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26570   if (X86::isZeroNode(N->getOperand(0)) &&
26571       X86::isZeroNode(N->getOperand(1)) &&
26572       // We don't have a good way to replace an EFLAGS use, so only do this when
26573       // dead right now.
26574       SDValue(N, 1).use_empty()) {
26575     SDLoc DL(N);
26576     EVT VT = N->getValueType(0);
26577     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26578     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26579                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26580                                            DAG.getConstant(X86::COND_B, DL,
26581                                                            MVT::i8),
26582                                            N->getOperand(2)),
26583                                DAG.getConstant(1, DL, VT));
26584     return DCI.CombineTo(N, Res1, CarryOut);
26585   }
26586
26587   return SDValue();
26588 }
26589
26590 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26591 //      (add Y, (setne X, 0)) -> sbb -1, Y
26592 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26593 //      (sub (setne X, 0), Y) -> adc -1, Y
26594 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26595   SDLoc DL(N);
26596
26597   // Look through ZExts.
26598   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26599   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26600     return SDValue();
26601
26602   SDValue SetCC = Ext.getOperand(0);
26603   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26604     return SDValue();
26605
26606   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26607   if (CC != X86::COND_E && CC != X86::COND_NE)
26608     return SDValue();
26609
26610   SDValue Cmp = SetCC.getOperand(1);
26611   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26612       !X86::isZeroNode(Cmp.getOperand(1)) ||
26613       !Cmp.getOperand(0).getValueType().isInteger())
26614     return SDValue();
26615
26616   SDValue CmpOp0 = Cmp.getOperand(0);
26617   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26618                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26619
26620   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26621   if (CC == X86::COND_NE)
26622     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26623                        DL, OtherVal.getValueType(), OtherVal,
26624                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26625                        NewCmp);
26626   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26627                      DL, OtherVal.getValueType(), OtherVal,
26628                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26629 }
26630
26631 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26632 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26633                                  const X86Subtarget *Subtarget) {
26634   EVT VT = N->getValueType(0);
26635   SDValue Op0 = N->getOperand(0);
26636   SDValue Op1 = N->getOperand(1);
26637
26638   // Try to synthesize horizontal adds from adds of shuffles.
26639   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26640        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26641       isHorizontalBinOp(Op0, Op1, true))
26642     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26643
26644   return OptimizeConditionalInDecrement(N, DAG);
26645 }
26646
26647 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26648                                  const X86Subtarget *Subtarget) {
26649   SDValue Op0 = N->getOperand(0);
26650   SDValue Op1 = N->getOperand(1);
26651
26652   // X86 can't encode an immediate LHS of a sub. See if we can push the
26653   // negation into a preceding instruction.
26654   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26655     // If the RHS of the sub is a XOR with one use and a constant, invert the
26656     // immediate. Then add one to the LHS of the sub so we can turn
26657     // X-Y -> X+~Y+1, saving one register.
26658     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26659         isa<ConstantSDNode>(Op1.getOperand(1))) {
26660       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26661       EVT VT = Op0.getValueType();
26662       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26663                                    Op1.getOperand(0),
26664                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26665       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26666                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26667     }
26668   }
26669
26670   // Try to synthesize horizontal adds from adds of shuffles.
26671   EVT VT = N->getValueType(0);
26672   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26673        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26674       isHorizontalBinOp(Op0, Op1, true))
26675     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26676
26677   return OptimizeConditionalInDecrement(N, DAG);
26678 }
26679
26680 /// performVZEXTCombine - Performs build vector combines
26681 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26682                                    TargetLowering::DAGCombinerInfo &DCI,
26683                                    const X86Subtarget *Subtarget) {
26684   SDLoc DL(N);
26685   MVT VT = N->getSimpleValueType(0);
26686   SDValue Op = N->getOperand(0);
26687   MVT OpVT = Op.getSimpleValueType();
26688   MVT OpEltVT = OpVT.getVectorElementType();
26689   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26690
26691   // (vzext (bitcast (vzext (x)) -> (vzext x)
26692   SDValue V = Op;
26693   while (V.getOpcode() == ISD::BITCAST)
26694     V = V.getOperand(0);
26695
26696   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26697     MVT InnerVT = V.getSimpleValueType();
26698     MVT InnerEltVT = InnerVT.getVectorElementType();
26699
26700     // If the element sizes match exactly, we can just do one larger vzext. This
26701     // is always an exact type match as vzext operates on integer types.
26702     if (OpEltVT == InnerEltVT) {
26703       assert(OpVT == InnerVT && "Types must match for vzext!");
26704       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26705     }
26706
26707     // The only other way we can combine them is if only a single element of the
26708     // inner vzext is used in the input to the outer vzext.
26709     if (InnerEltVT.getSizeInBits() < InputBits)
26710       return SDValue();
26711
26712     // In this case, the inner vzext is completely dead because we're going to
26713     // only look at bits inside of the low element. Just do the outer vzext on
26714     // a bitcast of the input to the inner.
26715     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26716   }
26717
26718   // Check if we can bypass extracting and re-inserting an element of an input
26719   // vector. Essentially:
26720   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26721   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26722       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26723       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26724     SDValue ExtractedV = V.getOperand(0);
26725     SDValue OrigV = ExtractedV.getOperand(0);
26726     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26727       if (ExtractIdx->getZExtValue() == 0) {
26728         MVT OrigVT = OrigV.getSimpleValueType();
26729         // Extract a subvector if necessary...
26730         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26731           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26732           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26733                                     OrigVT.getVectorNumElements() / Ratio);
26734           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26735                               DAG.getIntPtrConstant(0, DL));
26736         }
26737         Op = DAG.getBitcast(OpVT, OrigV);
26738         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26739       }
26740   }
26741
26742   return SDValue();
26743 }
26744
26745 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26746                                              DAGCombinerInfo &DCI) const {
26747   SelectionDAG &DAG = DCI.DAG;
26748   switch (N->getOpcode()) {
26749   default: break;
26750   case ISD::EXTRACT_VECTOR_ELT:
26751     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26752   case ISD::VSELECT:
26753   case ISD::SELECT:
26754   case X86ISD::SHRUNKBLEND:
26755     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26756   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
26757   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26758   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26759   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26760   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26761   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26762   case ISD::SHL:
26763   case ISD::SRA:
26764   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26765   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26766   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26767   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26768   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26769   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26770   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26771   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26772   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26773   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26774   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26775   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26776   case X86ISD::FXOR:
26777   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26778   case X86ISD::FMIN:
26779   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26780   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26781   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26782   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26783   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26784   case ISD::ANY_EXTEND:
26785   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26786   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26787   case ISD::SIGN_EXTEND_INREG:
26788     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26789   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26790   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26791   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26792   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26793   case X86ISD::SHUFP:       // Handle all target specific shuffles
26794   case X86ISD::PALIGNR:
26795   case X86ISD::UNPCKH:
26796   case X86ISD::UNPCKL:
26797   case X86ISD::MOVHLPS:
26798   case X86ISD::MOVLHPS:
26799   case X86ISD::PSHUFB:
26800   case X86ISD::PSHUFD:
26801   case X86ISD::PSHUFHW:
26802   case X86ISD::PSHUFLW:
26803   case X86ISD::MOVSS:
26804   case X86ISD::MOVSD:
26805   case X86ISD::VPERMILPI:
26806   case X86ISD::VPERM2X128:
26807   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26808   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26809   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26810   }
26811
26812   return SDValue();
26813 }
26814
26815 /// isTypeDesirableForOp - Return true if the target has native support for
26816 /// the specified value type and it is 'desirable' to use the type for the
26817 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26818 /// instruction encodings are longer and some i16 instructions are slow.
26819 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26820   if (!isTypeLegal(VT))
26821     return false;
26822   if (VT != MVT::i16)
26823     return true;
26824
26825   switch (Opc) {
26826   default:
26827     return true;
26828   case ISD::LOAD:
26829   case ISD::SIGN_EXTEND:
26830   case ISD::ZERO_EXTEND:
26831   case ISD::ANY_EXTEND:
26832   case ISD::SHL:
26833   case ISD::SRL:
26834   case ISD::SUB:
26835   case ISD::ADD:
26836   case ISD::MUL:
26837   case ISD::AND:
26838   case ISD::OR:
26839   case ISD::XOR:
26840     return false;
26841   }
26842 }
26843
26844 /// IsDesirableToPromoteOp - This method query the target whether it is
26845 /// beneficial for dag combiner to promote the specified node. If true, it
26846 /// should return the desired promotion type by reference.
26847 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26848   EVT VT = Op.getValueType();
26849   if (VT != MVT::i16)
26850     return false;
26851
26852   bool Promote = false;
26853   bool Commute = false;
26854   switch (Op.getOpcode()) {
26855   default: break;
26856   case ISD::LOAD: {
26857     LoadSDNode *LD = cast<LoadSDNode>(Op);
26858     // If the non-extending load has a single use and it's not live out, then it
26859     // might be folded.
26860     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26861                                                      Op.hasOneUse()*/) {
26862       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26863              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26864         // The only case where we'd want to promote LOAD (rather then it being
26865         // promoted as an operand is when it's only use is liveout.
26866         if (UI->getOpcode() != ISD::CopyToReg)
26867           return false;
26868       }
26869     }
26870     Promote = true;
26871     break;
26872   }
26873   case ISD::SIGN_EXTEND:
26874   case ISD::ZERO_EXTEND:
26875   case ISD::ANY_EXTEND:
26876     Promote = true;
26877     break;
26878   case ISD::SHL:
26879   case ISD::SRL: {
26880     SDValue N0 = Op.getOperand(0);
26881     // Look out for (store (shl (load), x)).
26882     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26883       return false;
26884     Promote = true;
26885     break;
26886   }
26887   case ISD::ADD:
26888   case ISD::MUL:
26889   case ISD::AND:
26890   case ISD::OR:
26891   case ISD::XOR:
26892     Commute = true;
26893     // fallthrough
26894   case ISD::SUB: {
26895     SDValue N0 = Op.getOperand(0);
26896     SDValue N1 = Op.getOperand(1);
26897     if (!Commute && MayFoldLoad(N1))
26898       return false;
26899     // Avoid disabling potential load folding opportunities.
26900     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26901       return false;
26902     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26903       return false;
26904     Promote = true;
26905   }
26906   }
26907
26908   PVT = MVT::i32;
26909   return Promote;
26910 }
26911
26912 //===----------------------------------------------------------------------===//
26913 //                           X86 Inline Assembly Support
26914 //===----------------------------------------------------------------------===//
26915
26916 // Helper to match a string separated by whitespace.
26917 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26918   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26919
26920   for (StringRef Piece : Pieces) {
26921     if (!S.startswith(Piece)) // Check if the piece matches.
26922       return false;
26923
26924     S = S.substr(Piece.size());
26925     StringRef::size_type Pos = S.find_first_not_of(" \t");
26926     if (Pos == 0) // We matched a prefix.
26927       return false;
26928
26929     S = S.substr(Pos);
26930   }
26931
26932   return S.empty();
26933 }
26934
26935 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26936
26937   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26938     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26939         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26940         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26941
26942       if (AsmPieces.size() == 3)
26943         return true;
26944       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26945         return true;
26946     }
26947   }
26948   return false;
26949 }
26950
26951 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26952   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26953
26954   std::string AsmStr = IA->getAsmString();
26955
26956   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26957   if (!Ty || Ty->getBitWidth() % 16 != 0)
26958     return false;
26959
26960   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26961   SmallVector<StringRef, 4> AsmPieces;
26962   SplitString(AsmStr, AsmPieces, ";\n");
26963
26964   switch (AsmPieces.size()) {
26965   default: return false;
26966   case 1:
26967     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26968     // we will turn this bswap into something that will be lowered to logical
26969     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26970     // lower so don't worry about this.
26971     // bswap $0
26972     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26973         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26974         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26975         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26976         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26977         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26978       // No need to check constraints, nothing other than the equivalent of
26979       // "=r,0" would be valid here.
26980       return IntrinsicLowering::LowerToByteSwap(CI);
26981     }
26982
26983     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26984     if (CI->getType()->isIntegerTy(16) &&
26985         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26986         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26987          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26988       AsmPieces.clear();
26989       StringRef ConstraintsStr = IA->getConstraintString();
26990       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26991       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26992       if (clobbersFlagRegisters(AsmPieces))
26993         return IntrinsicLowering::LowerToByteSwap(CI);
26994     }
26995     break;
26996   case 3:
26997     if (CI->getType()->isIntegerTy(32) &&
26998         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26999         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
27000         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
27001         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
27002       AsmPieces.clear();
27003       StringRef ConstraintsStr = IA->getConstraintString();
27004       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27005       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27006       if (clobbersFlagRegisters(AsmPieces))
27007         return IntrinsicLowering::LowerToByteSwap(CI);
27008     }
27009
27010     if (CI->getType()->isIntegerTy(64)) {
27011       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
27012       if (Constraints.size() >= 2 &&
27013           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
27014           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
27015         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
27016         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
27017             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
27018             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
27019           return IntrinsicLowering::LowerToByteSwap(CI);
27020       }
27021     }
27022     break;
27023   }
27024   return false;
27025 }
27026
27027 /// getConstraintType - Given a constraint letter, return the type of
27028 /// constraint it is for this target.
27029 X86TargetLowering::ConstraintType
27030 X86TargetLowering::getConstraintType(StringRef Constraint) const {
27031   if (Constraint.size() == 1) {
27032     switch (Constraint[0]) {
27033     case 'R':
27034     case 'q':
27035     case 'Q':
27036     case 'f':
27037     case 't':
27038     case 'u':
27039     case 'y':
27040     case 'x':
27041     case 'Y':
27042     case 'l':
27043       return C_RegisterClass;
27044     case 'a':
27045     case 'b':
27046     case 'c':
27047     case 'd':
27048     case 'S':
27049     case 'D':
27050     case 'A':
27051       return C_Register;
27052     case 'I':
27053     case 'J':
27054     case 'K':
27055     case 'L':
27056     case 'M':
27057     case 'N':
27058     case 'G':
27059     case 'C':
27060     case 'e':
27061     case 'Z':
27062       return C_Other;
27063     default:
27064       break;
27065     }
27066   }
27067   return TargetLowering::getConstraintType(Constraint);
27068 }
27069
27070 /// Examine constraint type and operand type and determine a weight value.
27071 /// This object must already have been set up with the operand type
27072 /// and the current alternative constraint selected.
27073 TargetLowering::ConstraintWeight
27074   X86TargetLowering::getSingleConstraintMatchWeight(
27075     AsmOperandInfo &info, const char *constraint) const {
27076   ConstraintWeight weight = CW_Invalid;
27077   Value *CallOperandVal = info.CallOperandVal;
27078     // If we don't have a value, we can't do a match,
27079     // but allow it at the lowest weight.
27080   if (!CallOperandVal)
27081     return CW_Default;
27082   Type *type = CallOperandVal->getType();
27083   // Look at the constraint type.
27084   switch (*constraint) {
27085   default:
27086     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
27087   case 'R':
27088   case 'q':
27089   case 'Q':
27090   case 'a':
27091   case 'b':
27092   case 'c':
27093   case 'd':
27094   case 'S':
27095   case 'D':
27096   case 'A':
27097     if (CallOperandVal->getType()->isIntegerTy())
27098       weight = CW_SpecificReg;
27099     break;
27100   case 'f':
27101   case 't':
27102   case 'u':
27103     if (type->isFloatingPointTy())
27104       weight = CW_SpecificReg;
27105     break;
27106   case 'y':
27107     if (type->isX86_MMXTy() && Subtarget->hasMMX())
27108       weight = CW_SpecificReg;
27109     break;
27110   case 'x':
27111   case 'Y':
27112     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27113         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27114       weight = CW_Register;
27115     break;
27116   case 'I':
27117     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27118       if (C->getZExtValue() <= 31)
27119         weight = CW_Constant;
27120     }
27121     break;
27122   case 'J':
27123     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27124       if (C->getZExtValue() <= 63)
27125         weight = CW_Constant;
27126     }
27127     break;
27128   case 'K':
27129     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27130       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27131         weight = CW_Constant;
27132     }
27133     break;
27134   case 'L':
27135     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27136       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27137         weight = CW_Constant;
27138     }
27139     break;
27140   case 'M':
27141     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27142       if (C->getZExtValue() <= 3)
27143         weight = CW_Constant;
27144     }
27145     break;
27146   case 'N':
27147     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27148       if (C->getZExtValue() <= 0xff)
27149         weight = CW_Constant;
27150     }
27151     break;
27152   case 'G':
27153   case 'C':
27154     if (isa<ConstantFP>(CallOperandVal)) {
27155       weight = CW_Constant;
27156     }
27157     break;
27158   case 'e':
27159     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27160       if ((C->getSExtValue() >= -0x80000000LL) &&
27161           (C->getSExtValue() <= 0x7fffffffLL))
27162         weight = CW_Constant;
27163     }
27164     break;
27165   case 'Z':
27166     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27167       if (C->getZExtValue() <= 0xffffffff)
27168         weight = CW_Constant;
27169     }
27170     break;
27171   }
27172   return weight;
27173 }
27174
27175 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27176 /// with another that has more specific requirements based on the type of the
27177 /// corresponding operand.
27178 const char *X86TargetLowering::
27179 LowerXConstraint(EVT ConstraintVT) const {
27180   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27181   // 'f' like normal targets.
27182   if (ConstraintVT.isFloatingPoint()) {
27183     if (Subtarget->hasSSE2())
27184       return "Y";
27185     if (Subtarget->hasSSE1())
27186       return "x";
27187   }
27188
27189   return TargetLowering::LowerXConstraint(ConstraintVT);
27190 }
27191
27192 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27193 /// vector.  If it is invalid, don't add anything to Ops.
27194 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27195                                                      std::string &Constraint,
27196                                                      std::vector<SDValue>&Ops,
27197                                                      SelectionDAG &DAG) const {
27198   SDValue Result;
27199
27200   // Only support length 1 constraints for now.
27201   if (Constraint.length() > 1) return;
27202
27203   char ConstraintLetter = Constraint[0];
27204   switch (ConstraintLetter) {
27205   default: break;
27206   case 'I':
27207     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27208       if (C->getZExtValue() <= 31) {
27209         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27210                                        Op.getValueType());
27211         break;
27212       }
27213     }
27214     return;
27215   case 'J':
27216     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27217       if (C->getZExtValue() <= 63) {
27218         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27219                                        Op.getValueType());
27220         break;
27221       }
27222     }
27223     return;
27224   case 'K':
27225     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27226       if (isInt<8>(C->getSExtValue())) {
27227         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27228                                        Op.getValueType());
27229         break;
27230       }
27231     }
27232     return;
27233   case 'L':
27234     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27235       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27236           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27237         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27238                                        Op.getValueType());
27239         break;
27240       }
27241     }
27242     return;
27243   case 'M':
27244     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27245       if (C->getZExtValue() <= 3) {
27246         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27247                                        Op.getValueType());
27248         break;
27249       }
27250     }
27251     return;
27252   case 'N':
27253     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27254       if (C->getZExtValue() <= 255) {
27255         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27256                                        Op.getValueType());
27257         break;
27258       }
27259     }
27260     return;
27261   case 'O':
27262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27263       if (C->getZExtValue() <= 127) {
27264         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27265                                        Op.getValueType());
27266         break;
27267       }
27268     }
27269     return;
27270   case 'e': {
27271     // 32-bit signed value
27272     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27273       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27274                                            C->getSExtValue())) {
27275         // Widen to 64 bits here to get it sign extended.
27276         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27277         break;
27278       }
27279     // FIXME gcc accepts some relocatable values here too, but only in certain
27280     // memory models; it's complicated.
27281     }
27282     return;
27283   }
27284   case 'Z': {
27285     // 32-bit unsigned value
27286     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27287       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27288                                            C->getZExtValue())) {
27289         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27290                                        Op.getValueType());
27291         break;
27292       }
27293     }
27294     // FIXME gcc accepts some relocatable values here too, but only in certain
27295     // memory models; it's complicated.
27296     return;
27297   }
27298   case 'i': {
27299     // Literal immediates are always ok.
27300     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27301       // Widen to 64 bits here to get it sign extended.
27302       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27303       break;
27304     }
27305
27306     // In any sort of PIC mode addresses need to be computed at runtime by
27307     // adding in a register or some sort of table lookup.  These can't
27308     // be used as immediates.
27309     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27310       return;
27311
27312     // If we are in non-pic codegen mode, we allow the address of a global (with
27313     // an optional displacement) to be used with 'i'.
27314     GlobalAddressSDNode *GA = nullptr;
27315     int64_t Offset = 0;
27316
27317     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27318     while (1) {
27319       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27320         Offset += GA->getOffset();
27321         break;
27322       } else if (Op.getOpcode() == ISD::ADD) {
27323         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27324           Offset += C->getZExtValue();
27325           Op = Op.getOperand(0);
27326           continue;
27327         }
27328       } else if (Op.getOpcode() == ISD::SUB) {
27329         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27330           Offset += -C->getZExtValue();
27331           Op = Op.getOperand(0);
27332           continue;
27333         }
27334       }
27335
27336       // Otherwise, this isn't something we can handle, reject it.
27337       return;
27338     }
27339
27340     const GlobalValue *GV = GA->getGlobal();
27341     // If we require an extra load to get this address, as in PIC mode, we
27342     // can't accept it.
27343     if (isGlobalStubReference(
27344             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27345       return;
27346
27347     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27348                                         GA->getValueType(0), Offset);
27349     break;
27350   }
27351   }
27352
27353   if (Result.getNode()) {
27354     Ops.push_back(Result);
27355     return;
27356   }
27357   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27358 }
27359
27360 std::pair<unsigned, const TargetRegisterClass *>
27361 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27362                                                 StringRef Constraint,
27363                                                 MVT VT) const {
27364   // First, see if this is a constraint that directly corresponds to an LLVM
27365   // register class.
27366   if (Constraint.size() == 1) {
27367     // GCC Constraint Letters
27368     switch (Constraint[0]) {
27369     default: break;
27370       // TODO: Slight differences here in allocation order and leaving
27371       // RIP in the class. Do they matter any more here than they do
27372       // in the normal allocation?
27373     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27374       if (Subtarget->is64Bit()) {
27375         if (VT == MVT::i32 || VT == MVT::f32)
27376           return std::make_pair(0U, &X86::GR32RegClass);
27377         if (VT == MVT::i16)
27378           return std::make_pair(0U, &X86::GR16RegClass);
27379         if (VT == MVT::i8 || VT == MVT::i1)
27380           return std::make_pair(0U, &X86::GR8RegClass);
27381         if (VT == MVT::i64 || VT == MVT::f64)
27382           return std::make_pair(0U, &X86::GR64RegClass);
27383         break;
27384       }
27385       // 32-bit fallthrough
27386     case 'Q':   // Q_REGS
27387       if (VT == MVT::i32 || VT == MVT::f32)
27388         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27389       if (VT == MVT::i16)
27390         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27391       if (VT == MVT::i8 || VT == MVT::i1)
27392         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27393       if (VT == MVT::i64)
27394         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27395       break;
27396     case 'r':   // GENERAL_REGS
27397     case 'l':   // INDEX_REGS
27398       if (VT == MVT::i8 || VT == MVT::i1)
27399         return std::make_pair(0U, &X86::GR8RegClass);
27400       if (VT == MVT::i16)
27401         return std::make_pair(0U, &X86::GR16RegClass);
27402       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27403         return std::make_pair(0U, &X86::GR32RegClass);
27404       return std::make_pair(0U, &X86::GR64RegClass);
27405     case 'R':   // LEGACY_REGS
27406       if (VT == MVT::i8 || VT == MVT::i1)
27407         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27408       if (VT == MVT::i16)
27409         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27410       if (VT == MVT::i32 || !Subtarget->is64Bit())
27411         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27412       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27413     case 'f':  // FP Stack registers.
27414       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27415       // value to the correct fpstack register class.
27416       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27417         return std::make_pair(0U, &X86::RFP32RegClass);
27418       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27419         return std::make_pair(0U, &X86::RFP64RegClass);
27420       return std::make_pair(0U, &X86::RFP80RegClass);
27421     case 'y':   // MMX_REGS if MMX allowed.
27422       if (!Subtarget->hasMMX()) break;
27423       return std::make_pair(0U, &X86::VR64RegClass);
27424     case 'Y':   // SSE_REGS if SSE2 allowed
27425       if (!Subtarget->hasSSE2()) break;
27426       // FALL THROUGH.
27427     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27428       if (!Subtarget->hasSSE1()) break;
27429
27430       switch (VT.SimpleTy) {
27431       default: break;
27432       // Scalar SSE types.
27433       case MVT::f32:
27434       case MVT::i32:
27435         return std::make_pair(0U, &X86::FR32RegClass);
27436       case MVT::f64:
27437       case MVT::i64:
27438         return std::make_pair(0U, &X86::FR64RegClass);
27439       // Vector types.
27440       case MVT::v16i8:
27441       case MVT::v8i16:
27442       case MVT::v4i32:
27443       case MVT::v2i64:
27444       case MVT::v4f32:
27445       case MVT::v2f64:
27446         return std::make_pair(0U, &X86::VR128RegClass);
27447       // AVX types.
27448       case MVT::v32i8:
27449       case MVT::v16i16:
27450       case MVT::v8i32:
27451       case MVT::v4i64:
27452       case MVT::v8f32:
27453       case MVT::v4f64:
27454         return std::make_pair(0U, &X86::VR256RegClass);
27455       case MVT::v8f64:
27456       case MVT::v16f32:
27457       case MVT::v16i32:
27458       case MVT::v8i64:
27459         return std::make_pair(0U, &X86::VR512RegClass);
27460       }
27461       break;
27462     }
27463   }
27464
27465   // Use the default implementation in TargetLowering to convert the register
27466   // constraint into a member of a register class.
27467   std::pair<unsigned, const TargetRegisterClass*> Res;
27468   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27469
27470   // Not found as a standard register?
27471   if (!Res.second) {
27472     // Map st(0) -> st(7) -> ST0
27473     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27474         tolower(Constraint[1]) == 's' &&
27475         tolower(Constraint[2]) == 't' &&
27476         Constraint[3] == '(' &&
27477         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27478         Constraint[5] == ')' &&
27479         Constraint[6] == '}') {
27480
27481       Res.first = X86::FP0+Constraint[4]-'0';
27482       Res.second = &X86::RFP80RegClass;
27483       return Res;
27484     }
27485
27486     // GCC allows "st(0)" to be called just plain "st".
27487     if (StringRef("{st}").equals_lower(Constraint)) {
27488       Res.first = X86::FP0;
27489       Res.second = &X86::RFP80RegClass;
27490       return Res;
27491     }
27492
27493     // flags -> EFLAGS
27494     if (StringRef("{flags}").equals_lower(Constraint)) {
27495       Res.first = X86::EFLAGS;
27496       Res.second = &X86::CCRRegClass;
27497       return Res;
27498     }
27499
27500     // 'A' means EAX + EDX.
27501     if (Constraint == "A") {
27502       Res.first = X86::EAX;
27503       Res.second = &X86::GR32_ADRegClass;
27504       return Res;
27505     }
27506     return Res;
27507   }
27508
27509   // Otherwise, check to see if this is a register class of the wrong value
27510   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27511   // turn into {ax},{dx}.
27512   // MVT::Other is used to specify clobber names.
27513   if (Res.second->hasType(VT) || VT == MVT::Other)
27514     return Res;   // Correct type already, nothing to do.
27515
27516   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27517   // return "eax". This should even work for things like getting 64bit integer
27518   // registers when given an f64 type.
27519   const TargetRegisterClass *Class = Res.second;
27520   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27521       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27522     unsigned Size = VT.getSizeInBits();
27523     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27524                                   : Size == 16 ? MVT::i16
27525                                   : Size == 32 ? MVT::i32
27526                                   : Size == 64 ? MVT::i64
27527                                   : MVT::Other;
27528     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27529     if (DestReg > 0) {
27530       Res.first = DestReg;
27531       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27532                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27533                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27534                  : &X86::GR64RegClass;
27535       assert(Res.second->contains(Res.first) && "Register in register class");
27536     } else {
27537       // No register found/type mismatch.
27538       Res.first = 0;
27539       Res.second = nullptr;
27540     }
27541   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27542              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27543              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27544              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27545              Class == &X86::VR512RegClass) {
27546     // Handle references to XMM physical registers that got mapped into the
27547     // wrong class.  This can happen with constraints like {xmm0} where the
27548     // target independent register mapper will just pick the first match it can
27549     // find, ignoring the required type.
27550
27551     if (VT == MVT::f32 || VT == MVT::i32)
27552       Res.second = &X86::FR32RegClass;
27553     else if (VT == MVT::f64 || VT == MVT::i64)
27554       Res.second = &X86::FR64RegClass;
27555     else if (X86::VR128RegClass.hasType(VT))
27556       Res.second = &X86::VR128RegClass;
27557     else if (X86::VR256RegClass.hasType(VT))
27558       Res.second = &X86::VR256RegClass;
27559     else if (X86::VR512RegClass.hasType(VT))
27560       Res.second = &X86::VR512RegClass;
27561     else {
27562       // Type mismatch and not a clobber: Return an error;
27563       Res.first = 0;
27564       Res.second = nullptr;
27565     }
27566   }
27567
27568   return Res;
27569 }
27570
27571 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27572                                             const AddrMode &AM, Type *Ty,
27573                                             unsigned AS) const {
27574   // Scaling factors are not free at all.
27575   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27576   // will take 2 allocations in the out of order engine instead of 1
27577   // for plain addressing mode, i.e. inst (reg1).
27578   // E.g.,
27579   // vaddps (%rsi,%drx), %ymm0, %ymm1
27580   // Requires two allocations (one for the load, one for the computation)
27581   // whereas:
27582   // vaddps (%rsi), %ymm0, %ymm1
27583   // Requires just 1 allocation, i.e., freeing allocations for other operations
27584   // and having less micro operations to execute.
27585   //
27586   // For some X86 architectures, this is even worse because for instance for
27587   // stores, the complex addressing mode forces the instruction to use the
27588   // "load" ports instead of the dedicated "store" port.
27589   // E.g., on Haswell:
27590   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27591   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27592   if (isLegalAddressingMode(DL, AM, Ty, AS))
27593     // Scale represents reg2 * scale, thus account for 1
27594     // as soon as we use a second register.
27595     return AM.Scale != 0;
27596   return -1;
27597 }
27598
27599 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27600   // Integer division on x86 is expensive. However, when aggressively optimizing
27601   // for code size, we prefer to use a div instruction, as it is usually smaller
27602   // than the alternative sequence.
27603   // The exception to this is vector division. Since x86 doesn't have vector
27604   // integer division, leaving the division as-is is a loss even in terms of
27605   // size, because it will have to be scalarized, while the alternative code
27606   // sequence can be performed in vector form.
27607   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27608                                    Attribute::MinSize);
27609   return OptSize && !VT.isVector();
27610 }
27611
27612 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27613        TargetLowering::ArgListTy& Args) const {
27614   // The MCU psABI requires some arguments to be passed in-register.
27615   // For regular calls, the inreg arguments are marked by the front-end.
27616   // However, for compiler generated library calls, we have to patch this
27617   // up here.
27618   if (!Subtarget->isTargetMCU() || !Args.size())
27619     return;
27620
27621   unsigned FreeRegs = 3;
27622   for (auto &Arg : Args) {
27623     // For library functions, we do not expect any fancy types.
27624     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27625     unsigned SizeInRegs = (Size + 31) / 32;
27626     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27627       continue;
27628
27629     Arg.isInReg = true;
27630     FreeRegs -= SizeInRegs;
27631     if (!FreeRegs)
27632       break;
27633   }
27634 }