X86: More efficient legalization of wide integer compares
[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   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
425   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
426   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
427   if (Subtarget->is64Bit()) {
428     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
429     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
430     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
431   }
432   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
433   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
434   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
435   // support continuation, user-level threading, and etc.. As a result, no
436   // other SjLj exception interfaces are implemented and please don't build
437   // your own exception handling based on them.
438   // LLVM/Clang supports zero-cost DWARF exception handling.
439   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
440   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
441
442   // Darwin ABI issue.
443   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
444   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
445   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
446   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
447   if (Subtarget->is64Bit())
448     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
449   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
450   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
453     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
454     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
455     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
456     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
457   }
458   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
459   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
460   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
461   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
462   if (Subtarget->is64Bit()) {
463     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
464     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
465     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
466   }
467
468   if (Subtarget->hasSSE1())
469     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
470
471   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
472
473   // Expand certain atomics
474   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
475     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
476     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
477     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
478   }
479
480   if (Subtarget->hasCmpxchg16b()) {
481     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
482   }
483
484   // FIXME - use subtarget debug flags
485   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
486       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
487     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
488   }
489
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
491   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492
493   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
494   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495
496   setOperationAction(ISD::TRAP, MVT::Other, Legal);
497   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498
499   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
500   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
501   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
502   if (Subtarget->is64Bit()) {
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
835     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
836     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
837     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
838
839     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
840     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
841     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
842     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
843
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
845     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
848     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
849
850     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
851     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
852     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
853     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
854
855     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
856     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
857     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
858     // ISD::CTTZ v2i64 - scalarization is faster.
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
861     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
862     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
863
864     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
865     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
866       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
867       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
868       setOperationAction(ISD::VSELECT,            VT, Custom);
869       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
870     }
871
872     // We support custom legalizing of sext and anyext loads for specific
873     // memory vector types which we can load as a scalar (or sequence of
874     // scalars) and extend in-register to a legal 128-bit vector type. For sext
875     // loads these must work with a single scalar load.
876     for (MVT VT : MVT::integer_vector_valuetypes()) {
877       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
878       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
879       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
882       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
883       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
884       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
885       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
886     }
887
888     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
890     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
892     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
893     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
894     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
895     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
896
897     if (Subtarget->is64Bit()) {
898       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
899       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
900     }
901
902     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
903     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
904       setOperationAction(ISD::AND,    VT, Promote);
905       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
906       setOperationAction(ISD::OR,     VT, Promote);
907       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
908       setOperationAction(ISD::XOR,    VT, Promote);
909       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
910       setOperationAction(ISD::LOAD,   VT, Promote);
911       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
912       setOperationAction(ISD::SELECT, VT, Promote);
913       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914     }
915
916     // Custom lower v2i64 and v2f64 selects.
917     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
918     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
919     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
920     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
921
922     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
924
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
958     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
959     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
960     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
961     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
962
963     // FIXME: Do we need to handle scalar-to-vector here?
964     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
965
966     // We directly match byte blends in the backend as they match the VSELECT
967     // condition form.
968     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
969
970     // SSE41 brings specific instructions for doing vector sign extend even in
971     // cases where we don't have SRA.
972     for (MVT VT : MVT::integer_vector_valuetypes()) {
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
974       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976     }
977
978     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
983     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
984     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
985
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
990     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
991     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
992
993     // i8 and i16 vectors are custom because the source register and source
994     // source memory operand types are not the same width.  f32 vectors are
995     // custom since the immediate controlling the insert encodes additional
996     // information.
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1001
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1005     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1006
1007     // FIXME: these should be Legal, but that's only for the case where
1008     // the index is constant.  For now custom expand to deal with that.
1009     if (Subtarget->is64Bit()) {
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1012     }
1013   }
1014
1015   if (Subtarget->hasSSE2()) {
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1019
1020     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1022
1023     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1024     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1025
1026     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1027     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1028
1029     // In the customized shift lowering, the legal cases in AVX2 will be
1030     // recognized.
1031     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1033
1034     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1035     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1036
1037     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1038     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1039   }
1040
1041   if (Subtarget->hasXOP()) {
1042     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1043     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1044     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1045     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1046     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1047     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1048     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1049     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1050   }
1051
1052   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1053     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1059
1060     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1063
1064     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1076
1077     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1089
1090     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1091     // even though v8i16 is a legal type.
1092     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1093     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1094     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1095
1096     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1097     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1098     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1099
1100     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1101     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1102
1103     for (MVT VT : MVT::fp_vector_valuetypes())
1104       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1105
1106     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1107     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1108
1109     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1110     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1111
1112     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1113     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1114
1115     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1116     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1117     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1118     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1119
1120     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1121     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1122     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1123
1124     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1125     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1126     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1127     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1128     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1129     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1130     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1131     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1132     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1133     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1134     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1135     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1136
1137     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1138     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1139     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1140     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1141
1142     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1143     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1144     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1145     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1146     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1147     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1148     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1149     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1150
1151     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1152       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1153       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1154       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1155       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1156       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1157       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1158     }
1159
1160     if (Subtarget->hasInt256()) {
1161       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1162       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1163       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1164       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1165
1166       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1167       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1168       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1169       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1170
1171       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1173       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1174       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1177       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1178       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1179       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1180
1181       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1182       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1183       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1184       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1185       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1186       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1187       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1188       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1189       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1190       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1191       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1192       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1193
1194       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1195       // when we have a 256bit-wide blend with immediate.
1196       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1197
1198       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1199       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1201       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1202       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1203       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1204       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1205
1206       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1208       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1209       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1210       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1211       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1212     } else {
1213       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1214       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1215       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1216       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1217
1218       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1219       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1220       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1221       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1222
1223       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1224       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1227
1228       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1229       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1230       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1231       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1232       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1233       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1234       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1235       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1236       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1237       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1238       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1239       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1240     }
1241
1242     // In the customized shift lowering, the legal cases in AVX2 will be
1243     // recognized.
1244     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1245     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1246
1247     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1248     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1249
1250     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1251     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1252
1253     // Custom lower several nodes for 256-bit types.
1254     for (MVT VT : MVT::vector_valuetypes()) {
1255       if (VT.getScalarSizeInBits() >= 32) {
1256         setOperationAction(ISD::MLOAD,  VT, Legal);
1257         setOperationAction(ISD::MSTORE, VT, Legal);
1258       }
1259       // Extract subvector is special because the value type
1260       // (result) is 128-bit but the source is 256-bit wide.
1261       if (VT.is128BitVector()) {
1262         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1263       }
1264       // Do not attempt to custom lower other non-256-bit vectors
1265       if (!VT.is256BitVector())
1266         continue;
1267
1268       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1269       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1270       setOperationAction(ISD::VSELECT,            VT, Custom);
1271       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1272       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1273       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1274       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1275       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1276     }
1277
1278     if (Subtarget->hasInt256())
1279       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1280
1281     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1282     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1283       setOperationAction(ISD::AND,    VT, Promote);
1284       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1285       setOperationAction(ISD::OR,     VT, Promote);
1286       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1287       setOperationAction(ISD::XOR,    VT, Promote);
1288       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1289       setOperationAction(ISD::LOAD,   VT, Promote);
1290       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1291       setOperationAction(ISD::SELECT, VT, Promote);
1292       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1293     }
1294   }
1295
1296   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1297     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1298     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1299     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1300     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1301
1302     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1303     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1304     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1305
1306     for (MVT VT : MVT::fp_vector_valuetypes())
1307       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1308
1309     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1310     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1311     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1312     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1313     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1314     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1315     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1316     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1317     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1318     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1319     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1320     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1321
1322     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1323     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1324     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1325     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1326     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1327     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1328     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1329     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1330     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1331     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1334     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1335     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1336
1337     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1341     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1342     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1343
1344     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1345     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1349     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1350     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1351     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1352
1353     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1355     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1356     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1357     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1359     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1360     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1361     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1363     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1364     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1365     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1366     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1367     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1368     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1369
1370     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1371     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1372     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1373     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1374     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1375     if (Subtarget->hasVLX()){
1376       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1377       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1378       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1379       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1380       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1381
1382       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1383       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1384       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1385       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1386       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1387     }
1388     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1389     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1390     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1391     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1392     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1393     if (Subtarget->hasDQI()) {
1394       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1395       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1396
1397       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1398       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1399       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1400       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1401       if (Subtarget->hasVLX()) {
1402         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1403         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1404         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1405         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1406         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1407         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1408         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1409         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1410       }
1411     }
1412     if (Subtarget->hasVLX()) {
1413       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1414       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1415       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1416       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1417       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1418       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1419       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1420       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1421     }
1422     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1423     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1425     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1426     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1427     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1428     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1429     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1434     if (Subtarget->hasDQI()) {
1435       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1436       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1437     }
1438     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1439     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1440     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1441     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1442     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1443     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1444     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1445     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1446     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1447     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1448
1449     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1450     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1451     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1452     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1453     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1454
1455     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1456     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1457
1458     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1459
1460     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1461     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1462     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1463     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1464     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1465     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1466     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1467     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1468     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1469     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1470     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1471
1472     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1473     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1474     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1475     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1476     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1477     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1478     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1479     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1480
1481     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1482     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1483
1484     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1485     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1486
1487     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1488
1489     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1490     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1491
1492     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1493     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1494
1495     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1496     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1497
1498     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1499     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1500     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1501     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1502     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1503     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1504
1505     if (Subtarget->hasCDI()) {
1506       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1507       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1508       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1509       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1510
1511       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1512       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1513       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1514       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1515       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1516       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1517       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1518       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1519
1520       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1521       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1522
1523       if (Subtarget->hasVLX()) {
1524         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1525         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1526         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1527         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1528         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1529         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1530         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1531         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1532
1533         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1534         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1535         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1536         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1537       } else {
1538         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1539         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1540         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1541         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1542         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1543         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1544         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1545         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1546       }
1547     } // Subtarget->hasCDI()
1548
1549     if (Subtarget->hasDQI()) {
1550       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1551       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1552       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1553     }
1554     // Custom lower several nodes.
1555     for (MVT VT : MVT::vector_valuetypes()) {
1556       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1557       if (EltSize == 1) {
1558         setOperationAction(ISD::AND, VT, Legal);
1559         setOperationAction(ISD::OR,  VT, Legal);
1560         setOperationAction(ISD::XOR,  VT, Legal);
1561       }
1562       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1563         setOperationAction(ISD::MGATHER,  VT, Custom);
1564         setOperationAction(ISD::MSCATTER, VT, Custom);
1565       }
1566       // Extract subvector is special because the value type
1567       // (result) is 256/128-bit but the source is 512-bit wide.
1568       if (VT.is128BitVector() || VT.is256BitVector()) {
1569         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1570       }
1571       if (VT.getVectorElementType() == MVT::i1)
1572         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1573
1574       // Do not attempt to custom lower other non-512-bit vectors
1575       if (!VT.is512BitVector())
1576         continue;
1577
1578       if (EltSize >= 32) {
1579         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1580         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1581         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1582         setOperationAction(ISD::VSELECT,             VT, Legal);
1583         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1584         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1585         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1586         setOperationAction(ISD::MLOAD,               VT, Legal);
1587         setOperationAction(ISD::MSTORE,              VT, Legal);
1588       }
1589     }
1590     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1591       setOperationAction(ISD::SELECT, VT, Promote);
1592       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1593     }
1594   }// has  AVX-512
1595
1596   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1597     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1598     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1599
1600     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1601     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1602
1603     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1604     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1605     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1606     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1607     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1608     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1609     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1610     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1611     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1612     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1613     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1614     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1615     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1616     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1617     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1618     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1619     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1620     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1621     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1622     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1623     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1624     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1625     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1626     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1627     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1628     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1629     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1630     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1631     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1632     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1633     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1634     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1635     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1636     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1637     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1638     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1639     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1640     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1641     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1642     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1643     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1644     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1645
1646     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1647     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1648     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1649     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1650     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1651     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1652     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1653     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1654
1655     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1656     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1657     if (Subtarget->hasVLX())
1658       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1659
1660     if (Subtarget->hasCDI()) {
1661       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1662       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1663       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1664       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1665     }
1666
1667     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1668       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1669       setOperationAction(ISD::VSELECT,             VT, Legal);
1670     }
1671   }
1672
1673   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1674     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1675     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1676
1677     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1678     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1679     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1680     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1681     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1682     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1683     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1684     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1685     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1686     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1687     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1688     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1689
1690     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1691     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1692     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1693     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1694     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1695     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1696     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1697     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1698
1699     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1700     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1701     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1702     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1703     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1704     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1705     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1706     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1707   }
1708
1709   // We want to custom lower some of our intrinsics.
1710   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1711   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1712   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1713   if (!Subtarget->is64Bit())
1714     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1715
1716   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1717   // handle type legalization for these operations here.
1718   //
1719   // FIXME: We really should do custom legalization for addition and
1720   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1721   // than generic legalization for 64-bit multiplication-with-overflow, though.
1722   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1723     if (VT == MVT::i64 && !Subtarget->is64Bit())
1724       continue;
1725     // Add/Sub/Mul with overflow operations are custom lowered.
1726     setOperationAction(ISD::SADDO, VT, Custom);
1727     setOperationAction(ISD::UADDO, VT, Custom);
1728     setOperationAction(ISD::SSUBO, VT, Custom);
1729     setOperationAction(ISD::USUBO, VT, Custom);
1730     setOperationAction(ISD::SMULO, VT, Custom);
1731     setOperationAction(ISD::UMULO, VT, Custom);
1732   }
1733
1734   if (!Subtarget->is64Bit()) {
1735     // These libcalls are not available in 32-bit.
1736     setLibcallName(RTLIB::SHL_I128, nullptr);
1737     setLibcallName(RTLIB::SRL_I128, nullptr);
1738     setLibcallName(RTLIB::SRA_I128, nullptr);
1739   }
1740
1741   // Combine sin / cos into one node or libcall if possible.
1742   if (Subtarget->hasSinCos()) {
1743     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1744     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1745     if (Subtarget->isTargetDarwin()) {
1746       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1747       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1748       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1749       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1750     }
1751   }
1752
1753   if (Subtarget->isTargetWin64()) {
1754     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1755     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1756     setOperationAction(ISD::SREM, MVT::i128, Custom);
1757     setOperationAction(ISD::UREM, MVT::i128, Custom);
1758     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1759     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1760   }
1761
1762   // We have target-specific dag combine patterns for the following nodes:
1763   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1764   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1765   setTargetDAGCombine(ISD::BITCAST);
1766   setTargetDAGCombine(ISD::VSELECT);
1767   setTargetDAGCombine(ISD::SELECT);
1768   setTargetDAGCombine(ISD::SHL);
1769   setTargetDAGCombine(ISD::SRA);
1770   setTargetDAGCombine(ISD::SRL);
1771   setTargetDAGCombine(ISD::OR);
1772   setTargetDAGCombine(ISD::AND);
1773   setTargetDAGCombine(ISD::ADD);
1774   setTargetDAGCombine(ISD::FADD);
1775   setTargetDAGCombine(ISD::FSUB);
1776   setTargetDAGCombine(ISD::FMA);
1777   setTargetDAGCombine(ISD::SUB);
1778   setTargetDAGCombine(ISD::LOAD);
1779   setTargetDAGCombine(ISD::MLOAD);
1780   setTargetDAGCombine(ISD::STORE);
1781   setTargetDAGCombine(ISD::MSTORE);
1782   setTargetDAGCombine(ISD::ZERO_EXTEND);
1783   setTargetDAGCombine(ISD::ANY_EXTEND);
1784   setTargetDAGCombine(ISD::SIGN_EXTEND);
1785   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1786   setTargetDAGCombine(ISD::SINT_TO_FP);
1787   setTargetDAGCombine(ISD::UINT_TO_FP);
1788   setTargetDAGCombine(ISD::SETCC);
1789   setTargetDAGCombine(ISD::BUILD_VECTOR);
1790   setTargetDAGCombine(ISD::MUL);
1791   setTargetDAGCombine(ISD::XOR);
1792
1793   computeRegisterProperties(Subtarget->getRegisterInfo());
1794
1795   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1796   MaxStoresPerMemsetOptSize = 8;
1797   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1798   MaxStoresPerMemcpyOptSize = 4;
1799   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1800   MaxStoresPerMemmoveOptSize = 4;
1801   setPrefLoopAlignment(4); // 2^4 bytes.
1802
1803   // A predictable cmov does not hurt on an in-order CPU.
1804   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1805   PredictableSelectIsExpensive = !Subtarget->isAtom();
1806   EnableExtLdPromotion = true;
1807   setPrefFunctionAlignment(4); // 2^4 bytes.
1808
1809   verifyIntrinsicTables();
1810 }
1811
1812 // This has so far only been implemented for 64-bit MachO.
1813 bool X86TargetLowering::useLoadStackGuardNode() const {
1814   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1815 }
1816
1817 TargetLoweringBase::LegalizeTypeAction
1818 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1819   if (ExperimentalVectorWideningLegalization &&
1820       VT.getVectorNumElements() != 1 &&
1821       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1822     return TypeWidenVector;
1823
1824   return TargetLoweringBase::getPreferredVectorAction(VT);
1825 }
1826
1827 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1828                                           EVT VT) const {
1829   if (!VT.isVector())
1830     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1831
1832   if (VT.isSimple()) {
1833     MVT VVT = VT.getSimpleVT();
1834     const unsigned NumElts = VVT.getVectorNumElements();
1835     const MVT EltVT = VVT.getVectorElementType();
1836     if (VVT.is512BitVector()) {
1837       if (Subtarget->hasAVX512())
1838         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1839             EltVT == MVT::f32 || EltVT == MVT::f64)
1840           switch(NumElts) {
1841           case  8: return MVT::v8i1;
1842           case 16: return MVT::v16i1;
1843         }
1844       if (Subtarget->hasBWI())
1845         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1846           switch(NumElts) {
1847           case 32: return MVT::v32i1;
1848           case 64: return MVT::v64i1;
1849         }
1850     }
1851
1852     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1853       if (Subtarget->hasVLX())
1854         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1855             EltVT == MVT::f32 || EltVT == MVT::f64)
1856           switch(NumElts) {
1857           case 2: return MVT::v2i1;
1858           case 4: return MVT::v4i1;
1859           case 8: return MVT::v8i1;
1860         }
1861       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1862         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1863           switch(NumElts) {
1864           case  8: return MVT::v8i1;
1865           case 16: return MVT::v16i1;
1866           case 32: return MVT::v32i1;
1867         }
1868     }
1869   }
1870
1871   return VT.changeVectorElementTypeToInteger();
1872 }
1873
1874 /// Helper for getByValTypeAlignment to determine
1875 /// the desired ByVal argument alignment.
1876 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1877   if (MaxAlign == 16)
1878     return;
1879   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1880     if (VTy->getBitWidth() == 128)
1881       MaxAlign = 16;
1882   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1883     unsigned EltAlign = 0;
1884     getMaxByValAlign(ATy->getElementType(), EltAlign);
1885     if (EltAlign > MaxAlign)
1886       MaxAlign = EltAlign;
1887   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1888     for (auto *EltTy : STy->elements()) {
1889       unsigned EltAlign = 0;
1890       getMaxByValAlign(EltTy, EltAlign);
1891       if (EltAlign > MaxAlign)
1892         MaxAlign = EltAlign;
1893       if (MaxAlign == 16)
1894         break;
1895     }
1896   }
1897 }
1898
1899 /// Return the desired alignment for ByVal aggregate
1900 /// function arguments in the caller parameter area. For X86, aggregates
1901 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1902 /// are at 4-byte boundaries.
1903 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1904                                                   const DataLayout &DL) const {
1905   if (Subtarget->is64Bit()) {
1906     // Max of 8 and alignment of type.
1907     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1908     if (TyAlign > 8)
1909       return TyAlign;
1910     return 8;
1911   }
1912
1913   unsigned Align = 4;
1914   if (Subtarget->hasSSE1())
1915     getMaxByValAlign(Ty, Align);
1916   return Align;
1917 }
1918
1919 /// Returns the target specific optimal type for load
1920 /// and store operations as a result of memset, memcpy, and memmove
1921 /// lowering. If DstAlign is zero that means it's safe to destination
1922 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1923 /// means there isn't a need to check it against alignment requirement,
1924 /// probably because the source does not need to be loaded. If 'IsMemset' is
1925 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1926 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1927 /// source is constant so it does not need to be loaded.
1928 /// It returns EVT::Other if the type should be determined using generic
1929 /// target-independent logic.
1930 EVT
1931 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1932                                        unsigned DstAlign, unsigned SrcAlign,
1933                                        bool IsMemset, bool ZeroMemset,
1934                                        bool MemcpyStrSrc,
1935                                        MachineFunction &MF) const {
1936   const Function *F = MF.getFunction();
1937   if ((!IsMemset || ZeroMemset) &&
1938       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1939     if (Size >= 16 &&
1940         (!Subtarget->isUnalignedMem16Slow() ||
1941          ((DstAlign == 0 || DstAlign >= 16) &&
1942           (SrcAlign == 0 || SrcAlign >= 16)))) {
1943       if (Size >= 32) {
1944         // FIXME: Check if unaligned 32-byte accesses are slow.
1945         if (Subtarget->hasInt256())
1946           return MVT::v8i32;
1947         if (Subtarget->hasFp256())
1948           return MVT::v8f32;
1949       }
1950       if (Subtarget->hasSSE2())
1951         return MVT::v4i32;
1952       if (Subtarget->hasSSE1())
1953         return MVT::v4f32;
1954     } else if (!MemcpyStrSrc && Size >= 8 &&
1955                !Subtarget->is64Bit() &&
1956                Subtarget->hasSSE2()) {
1957       // Do not use f64 to lower memcpy if source is string constant. It's
1958       // better to use i32 to avoid the loads.
1959       return MVT::f64;
1960     }
1961   }
1962   // This is a compromise. If we reach here, unaligned accesses may be slow on
1963   // this target. However, creating smaller, aligned accesses could be even
1964   // slower and would certainly be a lot more code.
1965   if (Subtarget->is64Bit() && Size >= 8)
1966     return MVT::i64;
1967   return MVT::i32;
1968 }
1969
1970 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1971   if (VT == MVT::f32)
1972     return X86ScalarSSEf32;
1973   else if (VT == MVT::f64)
1974     return X86ScalarSSEf64;
1975   return true;
1976 }
1977
1978 bool
1979 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1980                                                   unsigned,
1981                                                   unsigned,
1982                                                   bool *Fast) const {
1983   if (Fast) {
1984     switch (VT.getSizeInBits()) {
1985     default:
1986       // 8-byte and under are always assumed to be fast.
1987       *Fast = true;
1988       break;
1989     case 128:
1990       *Fast = !Subtarget->isUnalignedMem16Slow();
1991       break;
1992     case 256:
1993       *Fast = !Subtarget->isUnalignedMem32Slow();
1994       break;
1995     // TODO: What about AVX-512 (512-bit) accesses?
1996     }
1997   }
1998   // Misaligned accesses of any size are always allowed.
1999   return true;
2000 }
2001
2002 /// Return the entry encoding for a jump table in the
2003 /// current function.  The returned value is a member of the
2004 /// MachineJumpTableInfo::JTEntryKind enum.
2005 unsigned X86TargetLowering::getJumpTableEncoding() const {
2006   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2007   // symbol.
2008   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2009       Subtarget->isPICStyleGOT())
2010     return MachineJumpTableInfo::EK_Custom32;
2011
2012   // Otherwise, use the normal jump table encoding heuristics.
2013   return TargetLowering::getJumpTableEncoding();
2014 }
2015
2016 bool X86TargetLowering::useSoftFloat() const {
2017   return Subtarget->useSoftFloat();
2018 }
2019
2020 const MCExpr *
2021 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2022                                              const MachineBasicBlock *MBB,
2023                                              unsigned uid,MCContext &Ctx) const{
2024   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2025          Subtarget->isPICStyleGOT());
2026   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2027   // entries.
2028   return MCSymbolRefExpr::create(MBB->getSymbol(),
2029                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2030 }
2031
2032 /// Returns relocation base for the given PIC jumptable.
2033 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2034                                                     SelectionDAG &DAG) const {
2035   if (!Subtarget->is64Bit())
2036     // This doesn't have SDLoc associated with it, but is not really the
2037     // same as a Register.
2038     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2039                        getPointerTy(DAG.getDataLayout()));
2040   return Table;
2041 }
2042
2043 /// This returns the relocation base for the given PIC jumptable,
2044 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2045 const MCExpr *X86TargetLowering::
2046 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2047                              MCContext &Ctx) const {
2048   // X86-64 uses RIP relative addressing based on the jump table label.
2049   if (Subtarget->isPICStyleRIPRel())
2050     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2051
2052   // Otherwise, the reference is relative to the PIC base.
2053   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2054 }
2055
2056 std::pair<const TargetRegisterClass *, uint8_t>
2057 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2058                                            MVT VT) const {
2059   const TargetRegisterClass *RRC = nullptr;
2060   uint8_t Cost = 1;
2061   switch (VT.SimpleTy) {
2062   default:
2063     return TargetLowering::findRepresentativeClass(TRI, VT);
2064   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2065     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2066     break;
2067   case MVT::x86mmx:
2068     RRC = &X86::VR64RegClass;
2069     break;
2070   case MVT::f32: case MVT::f64:
2071   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2072   case MVT::v4f32: case MVT::v2f64:
2073   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2074   case MVT::v4f64:
2075     RRC = &X86::VR128RegClass;
2076     break;
2077   }
2078   return std::make_pair(RRC, Cost);
2079 }
2080
2081 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2082                                                unsigned &Offset) const {
2083   if (!Subtarget->isTargetLinux())
2084     return false;
2085
2086   if (Subtarget->is64Bit()) {
2087     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2088     Offset = 0x28;
2089     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2090       AddressSpace = 256;
2091     else
2092       AddressSpace = 257;
2093   } else {
2094     // %gs:0x14 on i386
2095     Offset = 0x14;
2096     AddressSpace = 256;
2097   }
2098   return true;
2099 }
2100
2101 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2102   if (!Subtarget->isTargetAndroid())
2103     return TargetLowering::getSafeStackPointerLocation(IRB);
2104
2105   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2106   // definition of TLS_SLOT_SAFESTACK in
2107   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2108   unsigned AddressSpace, Offset;
2109   if (Subtarget->is64Bit()) {
2110     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2111     Offset = 0x48;
2112     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2113       AddressSpace = 256;
2114     else
2115       AddressSpace = 257;
2116   } else {
2117     // %gs:0x24 on i386
2118     Offset = 0x24;
2119     AddressSpace = 256;
2120   }
2121
2122   return ConstantExpr::getIntToPtr(
2123       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2124       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2125 }
2126
2127 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2128                                             unsigned DestAS) const {
2129   assert(SrcAS != DestAS && "Expected different address spaces!");
2130
2131   return SrcAS < 256 && DestAS < 256;
2132 }
2133
2134 //===----------------------------------------------------------------------===//
2135 //               Return Value Calling Convention Implementation
2136 //===----------------------------------------------------------------------===//
2137
2138 #include "X86GenCallingConv.inc"
2139
2140 bool X86TargetLowering::CanLowerReturn(
2141     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2142     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2143   SmallVector<CCValAssign, 16> RVLocs;
2144   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2145   return CCInfo.CheckReturn(Outs, RetCC_X86);
2146 }
2147
2148 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2149   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2150   return ScratchRegs;
2151 }
2152
2153 SDValue
2154 X86TargetLowering::LowerReturn(SDValue Chain,
2155                                CallingConv::ID CallConv, bool isVarArg,
2156                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2157                                const SmallVectorImpl<SDValue> &OutVals,
2158                                SDLoc dl, SelectionDAG &DAG) const {
2159   MachineFunction &MF = DAG.getMachineFunction();
2160   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2161
2162   SmallVector<CCValAssign, 16> RVLocs;
2163   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2164   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2165
2166   SDValue Flag;
2167   SmallVector<SDValue, 6> RetOps;
2168   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2169   // Operand #1 = Bytes To Pop
2170   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2171                    MVT::i16));
2172
2173   // Copy the result values into the output registers.
2174   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2175     CCValAssign &VA = RVLocs[i];
2176     assert(VA.isRegLoc() && "Can only return in registers!");
2177     SDValue ValToCopy = OutVals[i];
2178     EVT ValVT = ValToCopy.getValueType();
2179
2180     // Promote values to the appropriate types.
2181     if (VA.getLocInfo() == CCValAssign::SExt)
2182       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2183     else if (VA.getLocInfo() == CCValAssign::ZExt)
2184       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2185     else if (VA.getLocInfo() == CCValAssign::AExt) {
2186       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2187         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2188       else
2189         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2190     }
2191     else if (VA.getLocInfo() == CCValAssign::BCvt)
2192       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2193
2194     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2195            "Unexpected FP-extend for return value.");
2196
2197     // If this is x86-64, and we disabled SSE, we can't return FP values,
2198     // or SSE or MMX vectors.
2199     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2200          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2201           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2202       report_fatal_error("SSE register return with SSE disabled");
2203     }
2204     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2205     // llvm-gcc has never done it right and no one has noticed, so this
2206     // should be OK for now.
2207     if (ValVT == MVT::f64 &&
2208         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2209       report_fatal_error("SSE2 register return with SSE2 disabled");
2210
2211     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2212     // the RET instruction and handled by the FP Stackifier.
2213     if (VA.getLocReg() == X86::FP0 ||
2214         VA.getLocReg() == X86::FP1) {
2215       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2216       // change the value to the FP stack register class.
2217       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2218         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2219       RetOps.push_back(ValToCopy);
2220       // Don't emit a copytoreg.
2221       continue;
2222     }
2223
2224     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2225     // which is returned in RAX / RDX.
2226     if (Subtarget->is64Bit()) {
2227       if (ValVT == MVT::x86mmx) {
2228         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2229           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2230           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2231                                   ValToCopy);
2232           // If we don't have SSE2 available, convert to v4f32 so the generated
2233           // register is legal.
2234           if (!Subtarget->hasSSE2())
2235             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2236         }
2237       }
2238     }
2239
2240     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2241     Flag = Chain.getValue(1);
2242     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2243   }
2244
2245   // All x86 ABIs require that for returning structs by value we copy
2246   // the sret argument into %rax/%eax (depending on ABI) for the return.
2247   // We saved the argument into a virtual register in the entry block,
2248   // so now we copy the value out and into %rax/%eax.
2249   //
2250   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2251   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2252   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2253   // either case FuncInfo->setSRetReturnReg() will have been called.
2254   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2255     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2256                                      getPointerTy(MF.getDataLayout()));
2257
2258     unsigned RetValReg
2259         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2260           X86::RAX : X86::EAX;
2261     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2262     Flag = Chain.getValue(1);
2263
2264     // RAX/EAX now acts like a return value.
2265     RetOps.push_back(
2266         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2267   }
2268
2269   RetOps[0] = Chain;  // Update chain.
2270
2271   // Add the flag if we have it.
2272   if (Flag.getNode())
2273     RetOps.push_back(Flag);
2274
2275   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2276 }
2277
2278 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2279   if (N->getNumValues() != 1)
2280     return false;
2281   if (!N->hasNUsesOfValue(1, 0))
2282     return false;
2283
2284   SDValue TCChain = Chain;
2285   SDNode *Copy = *N->use_begin();
2286   if (Copy->getOpcode() == ISD::CopyToReg) {
2287     // If the copy has a glue operand, we conservatively assume it isn't safe to
2288     // perform a tail call.
2289     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2290       return false;
2291     TCChain = Copy->getOperand(0);
2292   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2293     return false;
2294
2295   bool HasRet = false;
2296   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2297        UI != UE; ++UI) {
2298     if (UI->getOpcode() != X86ISD::RET_FLAG)
2299       return false;
2300     // If we are returning more than one value, we can definitely
2301     // not make a tail call see PR19530
2302     if (UI->getNumOperands() > 4)
2303       return false;
2304     if (UI->getNumOperands() == 4 &&
2305         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2306       return false;
2307     HasRet = true;
2308   }
2309
2310   if (!HasRet)
2311     return false;
2312
2313   Chain = TCChain;
2314   return true;
2315 }
2316
2317 EVT
2318 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2319                                             ISD::NodeType ExtendKind) const {
2320   MVT ReturnMVT;
2321   // TODO: Is this also valid on 32-bit?
2322   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2323     ReturnMVT = MVT::i8;
2324   else
2325     ReturnMVT = MVT::i32;
2326
2327   EVT MinVT = getRegisterType(Context, ReturnMVT);
2328   return VT.bitsLT(MinVT) ? MinVT : VT;
2329 }
2330
2331 /// Lower the result values of a call into the
2332 /// appropriate copies out of appropriate physical registers.
2333 ///
2334 SDValue
2335 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2336                                    CallingConv::ID CallConv, bool isVarArg,
2337                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2338                                    SDLoc dl, SelectionDAG &DAG,
2339                                    SmallVectorImpl<SDValue> &InVals) const {
2340
2341   // Assign locations to each value returned by this call.
2342   SmallVector<CCValAssign, 16> RVLocs;
2343   bool Is64Bit = Subtarget->is64Bit();
2344   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2345                  *DAG.getContext());
2346   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2347
2348   // Copy all of the result registers out of their specified physreg.
2349   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2350     CCValAssign &VA = RVLocs[i];
2351     EVT CopyVT = VA.getLocVT();
2352
2353     // If this is x86-64, and we disabled SSE, we can't return FP values
2354     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2355         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2356       report_fatal_error("SSE register return with SSE disabled");
2357     }
2358
2359     // If we prefer to use the value in xmm registers, copy it out as f80 and
2360     // use a truncate to move it from fp stack reg to xmm reg.
2361     bool RoundAfterCopy = false;
2362     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2363         isScalarFPTypeInSSEReg(VA.getValVT())) {
2364       CopyVT = MVT::f80;
2365       RoundAfterCopy = (CopyVT != VA.getLocVT());
2366     }
2367
2368     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2369                                CopyVT, InFlag).getValue(1);
2370     SDValue Val = Chain.getValue(0);
2371
2372     if (RoundAfterCopy)
2373       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2374                         // This truncation won't change the value.
2375                         DAG.getIntPtrConstant(1, dl));
2376
2377     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2378       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2379
2380     InFlag = Chain.getValue(2);
2381     InVals.push_back(Val);
2382   }
2383
2384   return Chain;
2385 }
2386
2387 //===----------------------------------------------------------------------===//
2388 //                C & StdCall & Fast Calling Convention implementation
2389 //===----------------------------------------------------------------------===//
2390 //  StdCall calling convention seems to be standard for many Windows' API
2391 //  routines and around. It differs from C calling convention just a little:
2392 //  callee should clean up the stack, not caller. Symbols should be also
2393 //  decorated in some fancy way :) It doesn't support any vector arguments.
2394 //  For info on fast calling convention see Fast Calling Convention (tail call)
2395 //  implementation LowerX86_32FastCCCallTo.
2396
2397 /// CallIsStructReturn - Determines whether a call uses struct return
2398 /// semantics.
2399 enum StructReturnType {
2400   NotStructReturn,
2401   RegStructReturn,
2402   StackStructReturn
2403 };
2404 static StructReturnType
2405 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2406   if (Outs.empty())
2407     return NotStructReturn;
2408
2409   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2410   if (!Flags.isSRet())
2411     return NotStructReturn;
2412   if (Flags.isInReg())
2413     return RegStructReturn;
2414   return StackStructReturn;
2415 }
2416
2417 /// Determines whether a function uses struct return semantics.
2418 static StructReturnType
2419 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2420   if (Ins.empty())
2421     return NotStructReturn;
2422
2423   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2424   if (!Flags.isSRet())
2425     return NotStructReturn;
2426   if (Flags.isInReg())
2427     return RegStructReturn;
2428   return StackStructReturn;
2429 }
2430
2431 /// Make a copy of an aggregate at address specified by "Src" to address
2432 /// "Dst" with size and alignment information specified by the specific
2433 /// parameter attribute. The copy will be passed as a byval function parameter.
2434 static SDValue
2435 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2436                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2437                           SDLoc dl) {
2438   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2439
2440   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2441                        /*isVolatile*/false, /*AlwaysInline=*/true,
2442                        /*isTailCall*/false,
2443                        MachinePointerInfo(), MachinePointerInfo());
2444 }
2445
2446 /// Return true if the calling convention is one that we can guarantee TCO for.
2447 static bool canGuaranteeTCO(CallingConv::ID CC) {
2448   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2449           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2450 }
2451
2452 /// Return true if we might ever do TCO for calls with this calling convention.
2453 static bool mayTailCallThisCC(CallingConv::ID CC) {
2454   switch (CC) {
2455   // C calling conventions:
2456   case CallingConv::C:
2457   case CallingConv::X86_64_Win64:
2458   case CallingConv::X86_64_SysV:
2459   // Callee pop conventions:
2460   case CallingConv::X86_ThisCall:
2461   case CallingConv::X86_StdCall:
2462   case CallingConv::X86_VectorCall:
2463   case CallingConv::X86_FastCall:
2464     return true;
2465   default:
2466     return canGuaranteeTCO(CC);
2467   }
2468 }
2469
2470 /// Return true if the function is being made into a tailcall target by
2471 /// changing its ABI.
2472 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2473   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2474 }
2475
2476 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2477   auto Attr =
2478       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2479   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2480     return false;
2481
2482   CallSite CS(CI);
2483   CallingConv::ID CalleeCC = CS.getCallingConv();
2484   if (!mayTailCallThisCC(CalleeCC))
2485     return false;
2486
2487   return true;
2488 }
2489
2490 SDValue
2491 X86TargetLowering::LowerMemArgument(SDValue Chain,
2492                                     CallingConv::ID CallConv,
2493                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2494                                     SDLoc dl, SelectionDAG &DAG,
2495                                     const CCValAssign &VA,
2496                                     MachineFrameInfo *MFI,
2497                                     unsigned i) const {
2498   // Create the nodes corresponding to a load from this parameter slot.
2499   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2500   bool AlwaysUseMutable = shouldGuaranteeTCO(
2501       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2502   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2503   EVT ValVT;
2504
2505   // If value is passed by pointer we have address passed instead of the value
2506   // itself.
2507   bool ExtendedInMem = VA.isExtInLoc() &&
2508     VA.getValVT().getScalarType() == MVT::i1;
2509
2510   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2511     ValVT = VA.getLocVT();
2512   else
2513     ValVT = VA.getValVT();
2514
2515   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2516   // changed with more analysis.
2517   // In case of tail call optimization mark all arguments mutable. Since they
2518   // could be overwritten by lowering of arguments in case of a tail call.
2519   if (Flags.isByVal()) {
2520     unsigned Bytes = Flags.getByValSize();
2521     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2522     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2523     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2524   } else {
2525     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2526                                     VA.getLocMemOffset(), isImmutable);
2527     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2528     SDValue Val = DAG.getLoad(
2529         ValVT, dl, Chain, FIN,
2530         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2531         false, false, 0);
2532     return ExtendedInMem ?
2533       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2534   }
2535 }
2536
2537 // FIXME: Get this from tablegen.
2538 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2539                                                 const X86Subtarget *Subtarget) {
2540   assert(Subtarget->is64Bit());
2541
2542   if (Subtarget->isCallingConvWin64(CallConv)) {
2543     static const MCPhysReg GPR64ArgRegsWin64[] = {
2544       X86::RCX, X86::RDX, X86::R8,  X86::R9
2545     };
2546     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2547   }
2548
2549   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2550     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2551   };
2552   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2553 }
2554
2555 // FIXME: Get this from tablegen.
2556 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2557                                                 CallingConv::ID CallConv,
2558                                                 const X86Subtarget *Subtarget) {
2559   assert(Subtarget->is64Bit());
2560   if (Subtarget->isCallingConvWin64(CallConv)) {
2561     // The XMM registers which might contain var arg parameters are shadowed
2562     // in their paired GPR.  So we only need to save the GPR to their home
2563     // slots.
2564     // TODO: __vectorcall will change this.
2565     return None;
2566   }
2567
2568   const Function *Fn = MF.getFunction();
2569   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2570   bool isSoftFloat = Subtarget->useSoftFloat();
2571   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2572          "SSE register cannot be used when SSE is disabled!");
2573   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2574     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2575     // registers.
2576     return None;
2577
2578   static const MCPhysReg XMMArgRegs64Bit[] = {
2579     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2580     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2581   };
2582   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2583 }
2584
2585 SDValue X86TargetLowering::LowerFormalArguments(
2586     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2587     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2588     SmallVectorImpl<SDValue> &InVals) const {
2589   MachineFunction &MF = DAG.getMachineFunction();
2590   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2591   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2592
2593   const Function* Fn = MF.getFunction();
2594   if (Fn->hasExternalLinkage() &&
2595       Subtarget->isTargetCygMing() &&
2596       Fn->getName() == "main")
2597     FuncInfo->setForceFramePointer(true);
2598
2599   MachineFrameInfo *MFI = MF.getFrameInfo();
2600   bool Is64Bit = Subtarget->is64Bit();
2601   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2602
2603   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2604          "Var args not supported with calling convention fastcc, ghc or hipe");
2605
2606   // Assign locations to all of the incoming arguments.
2607   SmallVector<CCValAssign, 16> ArgLocs;
2608   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2609
2610   // Allocate shadow area for Win64
2611   if (IsWin64)
2612     CCInfo.AllocateStack(32, 8);
2613
2614   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2615
2616   unsigned LastVal = ~0U;
2617   SDValue ArgValue;
2618   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2619     CCValAssign &VA = ArgLocs[i];
2620     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2621     // places.
2622     assert(VA.getValNo() != LastVal &&
2623            "Don't support value assigned to multiple locs yet");
2624     (void)LastVal;
2625     LastVal = VA.getValNo();
2626
2627     if (VA.isRegLoc()) {
2628       EVT RegVT = VA.getLocVT();
2629       const TargetRegisterClass *RC;
2630       if (RegVT == MVT::i32)
2631         RC = &X86::GR32RegClass;
2632       else if (Is64Bit && RegVT == MVT::i64)
2633         RC = &X86::GR64RegClass;
2634       else if (RegVT == MVT::f32)
2635         RC = &X86::FR32RegClass;
2636       else if (RegVT == MVT::f64)
2637         RC = &X86::FR64RegClass;
2638       else if (RegVT.is512BitVector())
2639         RC = &X86::VR512RegClass;
2640       else if (RegVT.is256BitVector())
2641         RC = &X86::VR256RegClass;
2642       else if (RegVT.is128BitVector())
2643         RC = &X86::VR128RegClass;
2644       else if (RegVT == MVT::x86mmx)
2645         RC = &X86::VR64RegClass;
2646       else if (RegVT == MVT::i1)
2647         RC = &X86::VK1RegClass;
2648       else if (RegVT == MVT::v8i1)
2649         RC = &X86::VK8RegClass;
2650       else if (RegVT == MVT::v16i1)
2651         RC = &X86::VK16RegClass;
2652       else if (RegVT == MVT::v32i1)
2653         RC = &X86::VK32RegClass;
2654       else if (RegVT == MVT::v64i1)
2655         RC = &X86::VK64RegClass;
2656       else
2657         llvm_unreachable("Unknown argument type!");
2658
2659       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2660       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2661
2662       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2663       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2664       // right size.
2665       if (VA.getLocInfo() == CCValAssign::SExt)
2666         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2667                                DAG.getValueType(VA.getValVT()));
2668       else if (VA.getLocInfo() == CCValAssign::ZExt)
2669         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2670                                DAG.getValueType(VA.getValVT()));
2671       else if (VA.getLocInfo() == CCValAssign::BCvt)
2672         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2673
2674       if (VA.isExtInLoc()) {
2675         // Handle MMX values passed in XMM regs.
2676         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2677           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2678         else
2679           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2680       }
2681     } else {
2682       assert(VA.isMemLoc());
2683       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2684     }
2685
2686     // If value is passed via pointer - do a load.
2687     if (VA.getLocInfo() == CCValAssign::Indirect)
2688       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2689                              MachinePointerInfo(), false, false, false, 0);
2690
2691     InVals.push_back(ArgValue);
2692   }
2693
2694   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2695     // All x86 ABIs require that for returning structs by value we copy the
2696     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2697     // the argument into a virtual register so that we can access it from the
2698     // return points.
2699     if (Ins[i].Flags.isSRet()) {
2700       unsigned Reg = FuncInfo->getSRetReturnReg();
2701       if (!Reg) {
2702         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2703         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2704         FuncInfo->setSRetReturnReg(Reg);
2705       }
2706       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2707       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2708       break;
2709     }
2710   }
2711
2712   unsigned StackSize = CCInfo.getNextStackOffset();
2713   // Align stack specially for tail calls.
2714   if (shouldGuaranteeTCO(CallConv,
2715                          MF.getTarget().Options.GuaranteedTailCallOpt))
2716     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2717
2718   // If the function takes variable number of arguments, make a frame index for
2719   // the start of the first vararg value... for expansion of llvm.va_start. We
2720   // can skip this if there are no va_start calls.
2721   if (MFI->hasVAStart() &&
2722       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2723                    CallConv != CallingConv::X86_ThisCall))) {
2724     FuncInfo->setVarArgsFrameIndex(
2725         MFI->CreateFixedObject(1, StackSize, true));
2726   }
2727
2728   // Figure out if XMM registers are in use.
2729   assert(!(Subtarget->useSoftFloat() &&
2730            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2731          "SSE register cannot be used when SSE is disabled!");
2732
2733   // 64-bit calling conventions support varargs and register parameters, so we
2734   // have to do extra work to spill them in the prologue.
2735   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2736     // Find the first unallocated argument registers.
2737     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2738     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2739     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2740     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2741     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2742            "SSE register cannot be used when SSE is disabled!");
2743
2744     // Gather all the live in physical registers.
2745     SmallVector<SDValue, 6> LiveGPRs;
2746     SmallVector<SDValue, 8> LiveXMMRegs;
2747     SDValue ALVal;
2748     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2749       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2750       LiveGPRs.push_back(
2751           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2752     }
2753     if (!ArgXMMs.empty()) {
2754       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2755       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2756       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2757         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2758         LiveXMMRegs.push_back(
2759             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2760       }
2761     }
2762
2763     if (IsWin64) {
2764       // Get to the caller-allocated home save location.  Add 8 to account
2765       // for the return address.
2766       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2767       FuncInfo->setRegSaveFrameIndex(
2768           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2769       // Fixup to set vararg frame on shadow area (4 x i64).
2770       if (NumIntRegs < 4)
2771         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2772     } else {
2773       // For X86-64, if there are vararg parameters that are passed via
2774       // registers, then we must store them to their spots on the stack so
2775       // they may be loaded by deferencing the result of va_next.
2776       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2777       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2778       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2779           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2780     }
2781
2782     // Store the integer parameter registers.
2783     SmallVector<SDValue, 8> MemOps;
2784     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2785                                       getPointerTy(DAG.getDataLayout()));
2786     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2787     for (SDValue Val : LiveGPRs) {
2788       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2789                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2790       SDValue Store =
2791           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2792                        MachinePointerInfo::getFixedStack(
2793                            DAG.getMachineFunction(),
2794                            FuncInfo->getRegSaveFrameIndex(), Offset),
2795                        false, false, 0);
2796       MemOps.push_back(Store);
2797       Offset += 8;
2798     }
2799
2800     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2801       // Now store the XMM (fp + vector) parameter registers.
2802       SmallVector<SDValue, 12> SaveXMMOps;
2803       SaveXMMOps.push_back(Chain);
2804       SaveXMMOps.push_back(ALVal);
2805       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2806                              FuncInfo->getRegSaveFrameIndex(), dl));
2807       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2808                              FuncInfo->getVarArgsFPOffset(), dl));
2809       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2810                         LiveXMMRegs.end());
2811       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2812                                    MVT::Other, SaveXMMOps));
2813     }
2814
2815     if (!MemOps.empty())
2816       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2817   }
2818
2819   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2820     // Find the largest legal vector type.
2821     MVT VecVT = MVT::Other;
2822     // FIXME: Only some x86_32 calling conventions support AVX512.
2823     if (Subtarget->hasAVX512() &&
2824         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2825                      CallConv == CallingConv::Intel_OCL_BI)))
2826       VecVT = MVT::v16f32;
2827     else if (Subtarget->hasAVX())
2828       VecVT = MVT::v8f32;
2829     else if (Subtarget->hasSSE2())
2830       VecVT = MVT::v4f32;
2831
2832     // We forward some GPRs and some vector types.
2833     SmallVector<MVT, 2> RegParmTypes;
2834     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2835     RegParmTypes.push_back(IntVT);
2836     if (VecVT != MVT::Other)
2837       RegParmTypes.push_back(VecVT);
2838
2839     // Compute the set of forwarded registers. The rest are scratch.
2840     SmallVectorImpl<ForwardedRegister> &Forwards =
2841         FuncInfo->getForwardedMustTailRegParms();
2842     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2843
2844     // Conservatively forward AL on x86_64, since it might be used for varargs.
2845     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2846       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2847       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2848     }
2849
2850     // Copy all forwards from physical to virtual registers.
2851     for (ForwardedRegister &F : Forwards) {
2852       // FIXME: Can we use a less constrained schedule?
2853       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2854       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2855       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2856     }
2857   }
2858
2859   // Some CCs need callee pop.
2860   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2861                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2862     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2863   } else {
2864     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2865     // If this is an sret function, the return should pop the hidden pointer.
2866     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2867         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2868         argsAreStructReturn(Ins) == StackStructReturn)
2869       FuncInfo->setBytesToPopOnReturn(4);
2870   }
2871
2872   if (!Is64Bit) {
2873     // RegSaveFrameIndex is X86-64 only.
2874     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2875     if (CallConv == CallingConv::X86_FastCall ||
2876         CallConv == CallingConv::X86_ThisCall)
2877       // fastcc functions can't have varargs.
2878       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2879   }
2880
2881   FuncInfo->setArgumentStackSize(StackSize);
2882
2883   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2884     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2885     if (Personality == EHPersonality::CoreCLR) {
2886       assert(Is64Bit);
2887       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2888       // that we'd prefer this slot be allocated towards the bottom of the frame
2889       // (i.e. near the stack pointer after allocating the frame).  Every
2890       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2891       // offset from the bottom of this and each funclet's frame must be the
2892       // same, so the size of funclets' (mostly empty) frames is dictated by
2893       // how far this slot is from the bottom (since they allocate just enough
2894       // space to accomodate holding this slot at the correct offset).
2895       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2896       EHInfo->PSPSymFrameIdx = PSPSymFI;
2897     }
2898   }
2899
2900   return Chain;
2901 }
2902
2903 SDValue
2904 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2905                                     SDValue StackPtr, SDValue Arg,
2906                                     SDLoc dl, SelectionDAG &DAG,
2907                                     const CCValAssign &VA,
2908                                     ISD::ArgFlagsTy Flags) const {
2909   unsigned LocMemOffset = VA.getLocMemOffset();
2910   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2911   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2912                        StackPtr, PtrOff);
2913   if (Flags.isByVal())
2914     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2915
2916   return DAG.getStore(
2917       Chain, dl, Arg, PtrOff,
2918       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2919       false, false, 0);
2920 }
2921
2922 /// Emit a load of return address if tail call
2923 /// optimization is performed and it is required.
2924 SDValue
2925 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2926                                            SDValue &OutRetAddr, SDValue Chain,
2927                                            bool IsTailCall, bool Is64Bit,
2928                                            int FPDiff, SDLoc dl) const {
2929   // Adjust the Return address stack slot.
2930   EVT VT = getPointerTy(DAG.getDataLayout());
2931   OutRetAddr = getReturnAddressFrameIndex(DAG);
2932
2933   // Load the "old" Return address.
2934   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2935                            false, false, false, 0);
2936   return SDValue(OutRetAddr.getNode(), 1);
2937 }
2938
2939 /// Emit a store of the return address if tail call
2940 /// optimization is performed and it is required (FPDiff!=0).
2941 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2942                                         SDValue Chain, SDValue RetAddrFrIdx,
2943                                         EVT PtrVT, unsigned SlotSize,
2944                                         int FPDiff, SDLoc dl) {
2945   // Store the return address to the appropriate stack slot.
2946   if (!FPDiff) return Chain;
2947   // Calculate the new stack slot for the return address.
2948   int NewReturnAddrFI =
2949     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2950                                          false);
2951   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2952   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2953                        MachinePointerInfo::getFixedStack(
2954                            DAG.getMachineFunction(), NewReturnAddrFI),
2955                        false, false, 0);
2956   return Chain;
2957 }
2958
2959 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2960 /// operation of specified width.
2961 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
2962                        SDValue V2) {
2963   unsigned NumElems = VT.getVectorNumElements();
2964   SmallVector<int, 8> Mask;
2965   Mask.push_back(NumElems);
2966   for (unsigned i = 1; i != NumElems; ++i)
2967     Mask.push_back(i);
2968   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2969 }
2970
2971 SDValue
2972 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2973                              SmallVectorImpl<SDValue> &InVals) const {
2974   SelectionDAG &DAG                     = CLI.DAG;
2975   SDLoc &dl                             = CLI.DL;
2976   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2977   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2978   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2979   SDValue Chain                         = CLI.Chain;
2980   SDValue Callee                        = CLI.Callee;
2981   CallingConv::ID CallConv              = CLI.CallConv;
2982   bool &isTailCall                      = CLI.IsTailCall;
2983   bool isVarArg                         = CLI.IsVarArg;
2984
2985   MachineFunction &MF = DAG.getMachineFunction();
2986   bool Is64Bit        = Subtarget->is64Bit();
2987   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2988   StructReturnType SR = callIsStructReturn(Outs);
2989   bool IsSibcall      = false;
2990   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2991   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2992
2993   if (Attr.getValueAsString() == "true")
2994     isTailCall = false;
2995
2996   if (Subtarget->isPICStyleGOT() &&
2997       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2998     // If we are using a GOT, disable tail calls to external symbols with
2999     // default visibility. Tail calling such a symbol requires using a GOT
3000     // relocation, which forces early binding of the symbol. This breaks code
3001     // that require lazy function symbol resolution. Using musttail or
3002     // GuaranteedTailCallOpt will override this.
3003     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3004     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3005                G->getGlobal()->hasDefaultVisibility()))
3006       isTailCall = false;
3007   }
3008
3009   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3010   if (IsMustTail) {
3011     // Force this to be a tail call.  The verifier rules are enough to ensure
3012     // that we can lower this successfully without moving the return address
3013     // around.
3014     isTailCall = true;
3015   } else if (isTailCall) {
3016     // Check if it's really possible to do a tail call.
3017     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3018                     isVarArg, SR != NotStructReturn,
3019                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3020                     Outs, OutVals, Ins, DAG);
3021
3022     // Sibcalls are automatically detected tailcalls which do not require
3023     // ABI changes.
3024     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3025       IsSibcall = true;
3026
3027     if (isTailCall)
3028       ++NumTailCalls;
3029   }
3030
3031   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3032          "Var args not supported with calling convention fastcc, ghc or hipe");
3033
3034   // Analyze operands of the call, assigning locations to each operand.
3035   SmallVector<CCValAssign, 16> ArgLocs;
3036   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3037
3038   // Allocate shadow area for Win64
3039   if (IsWin64)
3040     CCInfo.AllocateStack(32, 8);
3041
3042   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3043
3044   // Get a count of how many bytes are to be pushed on the stack.
3045   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3046   if (IsSibcall)
3047     // This is a sibcall. The memory operands are available in caller's
3048     // own caller's stack.
3049     NumBytes = 0;
3050   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3051            canGuaranteeTCO(CallConv))
3052     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3053
3054   int FPDiff = 0;
3055   if (isTailCall && !IsSibcall && !IsMustTail) {
3056     // Lower arguments at fp - stackoffset + fpdiff.
3057     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3058
3059     FPDiff = NumBytesCallerPushed - NumBytes;
3060
3061     // Set the delta of movement of the returnaddr stackslot.
3062     // But only set if delta is greater than previous delta.
3063     if (FPDiff < X86Info->getTCReturnAddrDelta())
3064       X86Info->setTCReturnAddrDelta(FPDiff);
3065   }
3066
3067   unsigned NumBytesToPush = NumBytes;
3068   unsigned NumBytesToPop = NumBytes;
3069
3070   // If we have an inalloca argument, all stack space has already been allocated
3071   // for us and be right at the top of the stack.  We don't support multiple
3072   // arguments passed in memory when using inalloca.
3073   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3074     NumBytesToPush = 0;
3075     if (!ArgLocs.back().isMemLoc())
3076       report_fatal_error("cannot use inalloca attribute on a register "
3077                          "parameter");
3078     if (ArgLocs.back().getLocMemOffset() != 0)
3079       report_fatal_error("any parameter with the inalloca attribute must be "
3080                          "the only memory argument");
3081   }
3082
3083   if (!IsSibcall)
3084     Chain = DAG.getCALLSEQ_START(
3085         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3086
3087   SDValue RetAddrFrIdx;
3088   // Load return address for tail calls.
3089   if (isTailCall && FPDiff)
3090     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3091                                     Is64Bit, FPDiff, dl);
3092
3093   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3094   SmallVector<SDValue, 8> MemOpChains;
3095   SDValue StackPtr;
3096
3097   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3098   // of tail call optimization arguments are handle later.
3099   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3100   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3101     // Skip inalloca arguments, they have already been written.
3102     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3103     if (Flags.isInAlloca())
3104       continue;
3105
3106     CCValAssign &VA = ArgLocs[i];
3107     EVT RegVT = VA.getLocVT();
3108     SDValue Arg = OutVals[i];
3109     bool isByVal = Flags.isByVal();
3110
3111     // Promote the value if needed.
3112     switch (VA.getLocInfo()) {
3113     default: llvm_unreachable("Unknown loc info!");
3114     case CCValAssign::Full: break;
3115     case CCValAssign::SExt:
3116       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3117       break;
3118     case CCValAssign::ZExt:
3119       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3120       break;
3121     case CCValAssign::AExt:
3122       if (Arg.getValueType().isVector() &&
3123           Arg.getValueType().getVectorElementType() == MVT::i1)
3124         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3125       else if (RegVT.is128BitVector()) {
3126         // Special case: passing MMX values in XMM registers.
3127         Arg = DAG.getBitcast(MVT::i64, Arg);
3128         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3129         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3130       } else
3131         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3132       break;
3133     case CCValAssign::BCvt:
3134       Arg = DAG.getBitcast(RegVT, Arg);
3135       break;
3136     case CCValAssign::Indirect: {
3137       // Store the argument.
3138       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3139       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3140       Chain = DAG.getStore(
3141           Chain, dl, Arg, SpillSlot,
3142           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3143           false, false, 0);
3144       Arg = SpillSlot;
3145       break;
3146     }
3147     }
3148
3149     if (VA.isRegLoc()) {
3150       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3151       if (isVarArg && IsWin64) {
3152         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3153         // shadow reg if callee is a varargs function.
3154         unsigned ShadowReg = 0;
3155         switch (VA.getLocReg()) {
3156         case X86::XMM0: ShadowReg = X86::RCX; break;
3157         case X86::XMM1: ShadowReg = X86::RDX; break;
3158         case X86::XMM2: ShadowReg = X86::R8; break;
3159         case X86::XMM3: ShadowReg = X86::R9; break;
3160         }
3161         if (ShadowReg)
3162           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3163       }
3164     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3165       assert(VA.isMemLoc());
3166       if (!StackPtr.getNode())
3167         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3168                                       getPointerTy(DAG.getDataLayout()));
3169       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3170                                              dl, DAG, VA, Flags));
3171     }
3172   }
3173
3174   if (!MemOpChains.empty())
3175     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3176
3177   if (Subtarget->isPICStyleGOT()) {
3178     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3179     // GOT pointer.
3180     if (!isTailCall) {
3181       RegsToPass.push_back(std::make_pair(
3182           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3183                                           getPointerTy(DAG.getDataLayout()))));
3184     } else {
3185       // If we are tail calling and generating PIC/GOT style code load the
3186       // address of the callee into ECX. The value in ecx is used as target of
3187       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3188       // for tail calls on PIC/GOT architectures. Normally we would just put the
3189       // address of GOT into ebx and then call target@PLT. But for tail calls
3190       // ebx would be restored (since ebx is callee saved) before jumping to the
3191       // target@PLT.
3192
3193       // Note: The actual moving to ECX is done further down.
3194       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3195       if (G && !G->getGlobal()->hasLocalLinkage() &&
3196           G->getGlobal()->hasDefaultVisibility())
3197         Callee = LowerGlobalAddress(Callee, DAG);
3198       else if (isa<ExternalSymbolSDNode>(Callee))
3199         Callee = LowerExternalSymbol(Callee, DAG);
3200     }
3201   }
3202
3203   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3204     // From AMD64 ABI document:
3205     // For calls that may call functions that use varargs or stdargs
3206     // (prototype-less calls or calls to functions containing ellipsis (...) in
3207     // the declaration) %al is used as hidden argument to specify the number
3208     // of SSE registers used. The contents of %al do not need to match exactly
3209     // the number of registers, but must be an ubound on the number of SSE
3210     // registers used and is in the range 0 - 8 inclusive.
3211
3212     // Count the number of XMM registers allocated.
3213     static const MCPhysReg XMMArgRegs[] = {
3214       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3215       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3216     };
3217     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3218     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3219            && "SSE registers cannot be used when SSE is disabled");
3220
3221     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3222                                         DAG.getConstant(NumXMMRegs, dl,
3223                                                         MVT::i8)));
3224   }
3225
3226   if (isVarArg && IsMustTail) {
3227     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3228     for (const auto &F : Forwards) {
3229       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3230       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3231     }
3232   }
3233
3234   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3235   // don't need this because the eligibility check rejects calls that require
3236   // shuffling arguments passed in memory.
3237   if (!IsSibcall && isTailCall) {
3238     // Force all the incoming stack arguments to be loaded from the stack
3239     // before any new outgoing arguments are stored to the stack, because the
3240     // outgoing stack slots may alias the incoming argument stack slots, and
3241     // the alias isn't otherwise explicit. This is slightly more conservative
3242     // than necessary, because it means that each store effectively depends
3243     // on every argument instead of just those arguments it would clobber.
3244     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3245
3246     SmallVector<SDValue, 8> MemOpChains2;
3247     SDValue FIN;
3248     int FI = 0;
3249     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3250       CCValAssign &VA = ArgLocs[i];
3251       if (VA.isRegLoc())
3252         continue;
3253       assert(VA.isMemLoc());
3254       SDValue Arg = OutVals[i];
3255       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3256       // Skip inalloca arguments.  They don't require any work.
3257       if (Flags.isInAlloca())
3258         continue;
3259       // Create frame index.
3260       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3261       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3262       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3263       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3264
3265       if (Flags.isByVal()) {
3266         // Copy relative to framepointer.
3267         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3268         if (!StackPtr.getNode())
3269           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3270                                         getPointerTy(DAG.getDataLayout()));
3271         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3272                              StackPtr, Source);
3273
3274         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3275                                                          ArgChain,
3276                                                          Flags, DAG, dl));
3277       } else {
3278         // Store relative to framepointer.
3279         MemOpChains2.push_back(DAG.getStore(
3280             ArgChain, dl, Arg, FIN,
3281             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3282             false, false, 0));
3283       }
3284     }
3285
3286     if (!MemOpChains2.empty())
3287       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3288
3289     // Store the return address to the appropriate stack slot.
3290     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3291                                      getPointerTy(DAG.getDataLayout()),
3292                                      RegInfo->getSlotSize(), FPDiff, dl);
3293   }
3294
3295   // Build a sequence of copy-to-reg nodes chained together with token chain
3296   // and flag operands which copy the outgoing args into registers.
3297   SDValue InFlag;
3298   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3299     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3300                              RegsToPass[i].second, InFlag);
3301     InFlag = Chain.getValue(1);
3302   }
3303
3304   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3305     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3306     // In the 64-bit large code model, we have to make all calls
3307     // through a register, since the call instruction's 32-bit
3308     // pc-relative offset may not be large enough to hold the whole
3309     // address.
3310   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3311     // If the callee is a GlobalAddress node (quite common, every direct call
3312     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3313     // it.
3314     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3315
3316     // We should use extra load for direct calls to dllimported functions in
3317     // non-JIT mode.
3318     const GlobalValue *GV = G->getGlobal();
3319     if (!GV->hasDLLImportStorageClass()) {
3320       unsigned char OpFlags = 0;
3321       bool ExtraLoad = false;
3322       unsigned WrapperKind = ISD::DELETED_NODE;
3323
3324       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3325       // external symbols most go through the PLT in PIC mode.  If the symbol
3326       // has hidden or protected visibility, or if it is static or local, then
3327       // we don't need to use the PLT - we can directly call it.
3328       if (Subtarget->isTargetELF() &&
3329           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3330           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3331         OpFlags = X86II::MO_PLT;
3332       } else if (Subtarget->isPICStyleStubAny() &&
3333                  !GV->isStrongDefinitionForLinker() &&
3334                  (!Subtarget->getTargetTriple().isMacOSX() ||
3335                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3336         // PC-relative references to external symbols should go through $stub,
3337         // unless we're building with the leopard linker or later, which
3338         // automatically synthesizes these stubs.
3339         OpFlags = X86II::MO_DARWIN_STUB;
3340       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3341                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3342         // If the function is marked as non-lazy, generate an indirect call
3343         // which loads from the GOT directly. This avoids runtime overhead
3344         // at the cost of eager binding (and one extra byte of encoding).
3345         OpFlags = X86II::MO_GOTPCREL;
3346         WrapperKind = X86ISD::WrapperRIP;
3347         ExtraLoad = true;
3348       }
3349
3350       Callee = DAG.getTargetGlobalAddress(
3351           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3352
3353       // Add a wrapper if needed.
3354       if (WrapperKind != ISD::DELETED_NODE)
3355         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3356                              getPointerTy(DAG.getDataLayout()), Callee);
3357       // Add extra indirection if needed.
3358       if (ExtraLoad)
3359         Callee = DAG.getLoad(
3360             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3361             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3362             false, 0);
3363     }
3364   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3365     unsigned char OpFlags = 0;
3366
3367     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3368     // external symbols should go through the PLT.
3369     if (Subtarget->isTargetELF() &&
3370         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3371       OpFlags = X86II::MO_PLT;
3372     } else if (Subtarget->isPICStyleStubAny() &&
3373                (!Subtarget->getTargetTriple().isMacOSX() ||
3374                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3375       // PC-relative references to external symbols should go through $stub,
3376       // unless we're building with the leopard linker or later, which
3377       // automatically synthesizes these stubs.
3378       OpFlags = X86II::MO_DARWIN_STUB;
3379     }
3380
3381     Callee = DAG.getTargetExternalSymbol(
3382         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3383   } else if (Subtarget->isTarget64BitILP32() &&
3384              Callee->getValueType(0) == MVT::i32) {
3385     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3386     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3387   }
3388
3389   // Returns a chain & a flag for retval copy to use.
3390   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3391   SmallVector<SDValue, 8> Ops;
3392
3393   if (!IsSibcall && isTailCall) {
3394     Chain = DAG.getCALLSEQ_END(Chain,
3395                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3396                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3397     InFlag = Chain.getValue(1);
3398   }
3399
3400   Ops.push_back(Chain);
3401   Ops.push_back(Callee);
3402
3403   if (isTailCall)
3404     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3405
3406   // Add argument registers to the end of the list so that they are known live
3407   // into the call.
3408   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3409     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3410                                   RegsToPass[i].second.getValueType()));
3411
3412   // Add a register mask operand representing the call-preserved registers.
3413   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3414   assert(Mask && "Missing call preserved mask for calling convention");
3415
3416   // If this is an invoke in a 32-bit function using a funclet-based
3417   // personality, assume the function clobbers all registers. If an exception
3418   // is thrown, the runtime will not restore CSRs.
3419   // FIXME: Model this more precisely so that we can register allocate across
3420   // the normal edge and spill and fill across the exceptional edge.
3421   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3422     const Function *CallerFn = MF.getFunction();
3423     EHPersonality Pers =
3424         CallerFn->hasPersonalityFn()
3425             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3426             : EHPersonality::Unknown;
3427     if (isFuncletEHPersonality(Pers))
3428       Mask = RegInfo->getNoPreservedMask();
3429   }
3430
3431   Ops.push_back(DAG.getRegisterMask(Mask));
3432
3433   if (InFlag.getNode())
3434     Ops.push_back(InFlag);
3435
3436   if (isTailCall) {
3437     // We used to do:
3438     //// If this is the first return lowered for this function, add the regs
3439     //// to the liveout set for the function.
3440     // This isn't right, although it's probably harmless on x86; liveouts
3441     // should be computed from returns not tail calls.  Consider a void
3442     // function making a tail call to a function returning int.
3443     MF.getFrameInfo()->setHasTailCall();
3444     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3445   }
3446
3447   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3448   InFlag = Chain.getValue(1);
3449
3450   // Create the CALLSEQ_END node.
3451   unsigned NumBytesForCalleeToPop;
3452   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3453                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3454     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3455   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3456            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3457            SR == StackStructReturn)
3458     // If this is a call to a struct-return function, the callee
3459     // pops the hidden struct pointer, so we have to push it back.
3460     // This is common for Darwin/X86, Linux & Mingw32 targets.
3461     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3462     NumBytesForCalleeToPop = 4;
3463   else
3464     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3465
3466   // Returns a flag for retval copy to use.
3467   if (!IsSibcall) {
3468     Chain = DAG.getCALLSEQ_END(Chain,
3469                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3470                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3471                                                      true),
3472                                InFlag, dl);
3473     InFlag = Chain.getValue(1);
3474   }
3475
3476   // Handle result values, copying them out of physregs into vregs that we
3477   // return.
3478   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3479                          Ins, dl, DAG, InVals);
3480 }
3481
3482 //===----------------------------------------------------------------------===//
3483 //                Fast Calling Convention (tail call) implementation
3484 //===----------------------------------------------------------------------===//
3485
3486 //  Like std call, callee cleans arguments, convention except that ECX is
3487 //  reserved for storing the tail called function address. Only 2 registers are
3488 //  free for argument passing (inreg). Tail call optimization is performed
3489 //  provided:
3490 //                * tailcallopt is enabled
3491 //                * caller/callee are fastcc
3492 //  On X86_64 architecture with GOT-style position independent code only local
3493 //  (within module) calls are supported at the moment.
3494 //  To keep the stack aligned according to platform abi the function
3495 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3496 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3497 //  If a tail called function callee has more arguments than the caller the
3498 //  caller needs to make sure that there is room to move the RETADDR to. This is
3499 //  achieved by reserving an area the size of the argument delta right after the
3500 //  original RETADDR, but before the saved framepointer or the spilled registers
3501 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3502 //  stack layout:
3503 //    arg1
3504 //    arg2
3505 //    RETADDR
3506 //    [ new RETADDR
3507 //      move area ]
3508 //    (possible EBP)
3509 //    ESI
3510 //    EDI
3511 //    local1 ..
3512
3513 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3514 /// requirement.
3515 unsigned
3516 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3517                                                SelectionDAG& DAG) const {
3518   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3519   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3520   unsigned StackAlignment = TFI.getStackAlignment();
3521   uint64_t AlignMask = StackAlignment - 1;
3522   int64_t Offset = StackSize;
3523   unsigned SlotSize = RegInfo->getSlotSize();
3524   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3525     // Number smaller than 12 so just add the difference.
3526     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3527   } else {
3528     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3529     Offset = ((~AlignMask) & Offset) + StackAlignment +
3530       (StackAlignment-SlotSize);
3531   }
3532   return Offset;
3533 }
3534
3535 /// Return true if the given stack call argument is already available in the
3536 /// same position (relatively) of the caller's incoming argument stack.
3537 static
3538 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3539                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3540                          const X86InstrInfo *TII) {
3541   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3542   int FI = INT_MAX;
3543   if (Arg.getOpcode() == ISD::CopyFromReg) {
3544     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3545     if (!TargetRegisterInfo::isVirtualRegister(VR))
3546       return false;
3547     MachineInstr *Def = MRI->getVRegDef(VR);
3548     if (!Def)
3549       return false;
3550     if (!Flags.isByVal()) {
3551       if (!TII->isLoadFromStackSlot(Def, FI))
3552         return false;
3553     } else {
3554       unsigned Opcode = Def->getOpcode();
3555       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3556            Opcode == X86::LEA64_32r) &&
3557           Def->getOperand(1).isFI()) {
3558         FI = Def->getOperand(1).getIndex();
3559         Bytes = Flags.getByValSize();
3560       } else
3561         return false;
3562     }
3563   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3564     if (Flags.isByVal())
3565       // ByVal argument is passed in as a pointer but it's now being
3566       // dereferenced. e.g.
3567       // define @foo(%struct.X* %A) {
3568       //   tail call @bar(%struct.X* byval %A)
3569       // }
3570       return false;
3571     SDValue Ptr = Ld->getBasePtr();
3572     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3573     if (!FINode)
3574       return false;
3575     FI = FINode->getIndex();
3576   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3577     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3578     FI = FINode->getIndex();
3579     Bytes = Flags.getByValSize();
3580   } else
3581     return false;
3582
3583   assert(FI != INT_MAX);
3584   if (!MFI->isFixedObjectIndex(FI))
3585     return false;
3586   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3587 }
3588
3589 /// Check whether the call is eligible for tail call optimization. Targets
3590 /// that want to do tail call optimization should implement this function.
3591 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3592     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3593     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3594     const SmallVectorImpl<ISD::OutputArg> &Outs,
3595     const SmallVectorImpl<SDValue> &OutVals,
3596     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3597   if (!mayTailCallThisCC(CalleeCC))
3598     return false;
3599
3600   // If -tailcallopt is specified, make fastcc functions tail-callable.
3601   MachineFunction &MF = DAG.getMachineFunction();
3602   const Function *CallerF = MF.getFunction();
3603
3604   // If the function return type is x86_fp80 and the callee return type is not,
3605   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3606   // perform a tailcall optimization here.
3607   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3608     return false;
3609
3610   CallingConv::ID CallerCC = CallerF->getCallingConv();
3611   bool CCMatch = CallerCC == CalleeCC;
3612   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3613   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3614
3615   // Win64 functions have extra shadow space for argument homing. Don't do the
3616   // sibcall if the caller and callee have mismatched expectations for this
3617   // space.
3618   if (IsCalleeWin64 != IsCallerWin64)
3619     return false;
3620
3621   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3622     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3623       return true;
3624     return false;
3625   }
3626
3627   // Look for obvious safe cases to perform tail call optimization that do not
3628   // require ABI changes. This is what gcc calls sibcall.
3629
3630   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3631   // emit a special epilogue.
3632   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3633   if (RegInfo->needsStackRealignment(MF))
3634     return false;
3635
3636   // Also avoid sibcall optimization if either caller or callee uses struct
3637   // return semantics.
3638   if (isCalleeStructRet || isCallerStructRet)
3639     return false;
3640
3641   // Do not sibcall optimize vararg calls unless all arguments are passed via
3642   // registers.
3643   if (isVarArg && !Outs.empty()) {
3644     // Optimizing for varargs on Win64 is unlikely to be safe without
3645     // additional testing.
3646     if (IsCalleeWin64 || IsCallerWin64)
3647       return false;
3648
3649     SmallVector<CCValAssign, 16> ArgLocs;
3650     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3651                    *DAG.getContext());
3652
3653     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3654     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3655       if (!ArgLocs[i].isRegLoc())
3656         return false;
3657   }
3658
3659   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3660   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3661   // this into a sibcall.
3662   bool Unused = false;
3663   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3664     if (!Ins[i].Used) {
3665       Unused = true;
3666       break;
3667     }
3668   }
3669   if (Unused) {
3670     SmallVector<CCValAssign, 16> RVLocs;
3671     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3672                    *DAG.getContext());
3673     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3674     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3675       CCValAssign &VA = RVLocs[i];
3676       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3677         return false;
3678     }
3679   }
3680
3681   // If the calling conventions do not match, then we'd better make sure the
3682   // results are returned in the same way as what the caller expects.
3683   if (!CCMatch) {
3684     SmallVector<CCValAssign, 16> RVLocs1;
3685     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3686                     *DAG.getContext());
3687     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3688
3689     SmallVector<CCValAssign, 16> RVLocs2;
3690     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3691                     *DAG.getContext());
3692     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3693
3694     if (RVLocs1.size() != RVLocs2.size())
3695       return false;
3696     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3697       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3698         return false;
3699       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3700         return false;
3701       if (RVLocs1[i].isRegLoc()) {
3702         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3703           return false;
3704       } else {
3705         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3706           return false;
3707       }
3708     }
3709   }
3710
3711   unsigned StackArgsSize = 0;
3712
3713   // If the callee takes no arguments then go on to check the results of the
3714   // call.
3715   if (!Outs.empty()) {
3716     // Check if stack adjustment is needed. For now, do not do this if any
3717     // argument is passed on the stack.
3718     SmallVector<CCValAssign, 16> ArgLocs;
3719     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3720                    *DAG.getContext());
3721
3722     // Allocate shadow area for Win64
3723     if (IsCalleeWin64)
3724       CCInfo.AllocateStack(32, 8);
3725
3726     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3727     StackArgsSize = CCInfo.getNextStackOffset();
3728
3729     if (CCInfo.getNextStackOffset()) {
3730       // Check if the arguments are already laid out in the right way as
3731       // the caller's fixed stack objects.
3732       MachineFrameInfo *MFI = MF.getFrameInfo();
3733       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3734       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3735       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3736         CCValAssign &VA = ArgLocs[i];
3737         SDValue Arg = OutVals[i];
3738         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3739         if (VA.getLocInfo() == CCValAssign::Indirect)
3740           return false;
3741         if (!VA.isRegLoc()) {
3742           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3743                                    MFI, MRI, TII))
3744             return false;
3745         }
3746       }
3747     }
3748
3749     // If the tailcall address may be in a register, then make sure it's
3750     // possible to register allocate for it. In 32-bit, the call address can
3751     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3752     // callee-saved registers are restored. These happen to be the same
3753     // registers used to pass 'inreg' arguments so watch out for those.
3754     if (!Subtarget->is64Bit() &&
3755         ((!isa<GlobalAddressSDNode>(Callee) &&
3756           !isa<ExternalSymbolSDNode>(Callee)) ||
3757          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3758       unsigned NumInRegs = 0;
3759       // In PIC we need an extra register to formulate the address computation
3760       // for the callee.
3761       unsigned MaxInRegs =
3762         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3763
3764       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3765         CCValAssign &VA = ArgLocs[i];
3766         if (!VA.isRegLoc())
3767           continue;
3768         unsigned Reg = VA.getLocReg();
3769         switch (Reg) {
3770         default: break;
3771         case X86::EAX: case X86::EDX: case X86::ECX:
3772           if (++NumInRegs == MaxInRegs)
3773             return false;
3774           break;
3775         }
3776       }
3777     }
3778   }
3779
3780   bool CalleeWillPop =
3781       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3782                        MF.getTarget().Options.GuaranteedTailCallOpt);
3783
3784   if (unsigned BytesToPop =
3785           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3786     // If we have bytes to pop, the callee must pop them.
3787     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3788     if (!CalleePopMatches)
3789       return false;
3790   } else if (CalleeWillPop && StackArgsSize > 0) {
3791     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3792     return false;
3793   }
3794
3795   return true;
3796 }
3797
3798 FastISel *
3799 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3800                                   const TargetLibraryInfo *libInfo) const {
3801   return X86::createFastISel(funcInfo, libInfo);
3802 }
3803
3804 //===----------------------------------------------------------------------===//
3805 //                           Other Lowering Hooks
3806 //===----------------------------------------------------------------------===//
3807
3808 static bool MayFoldLoad(SDValue Op) {
3809   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3810 }
3811
3812 static bool MayFoldIntoStore(SDValue Op) {
3813   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3814 }
3815
3816 static bool isTargetShuffle(unsigned Opcode) {
3817   switch(Opcode) {
3818   default: return false;
3819   case X86ISD::BLENDI:
3820   case X86ISD::PSHUFB:
3821   case X86ISD::PSHUFD:
3822   case X86ISD::PSHUFHW:
3823   case X86ISD::PSHUFLW:
3824   case X86ISD::SHUFP:
3825   case X86ISD::PALIGNR:
3826   case X86ISD::MOVLHPS:
3827   case X86ISD::MOVLHPD:
3828   case X86ISD::MOVHLPS:
3829   case X86ISD::MOVLPS:
3830   case X86ISD::MOVLPD:
3831   case X86ISD::MOVSHDUP:
3832   case X86ISD::MOVSLDUP:
3833   case X86ISD::MOVDDUP:
3834   case X86ISD::MOVSS:
3835   case X86ISD::MOVSD:
3836   case X86ISD::UNPCKL:
3837   case X86ISD::UNPCKH:
3838   case X86ISD::VPERMILPI:
3839   case X86ISD::VPERM2X128:
3840   case X86ISD::VPERMI:
3841   case X86ISD::VPERMV:
3842   case X86ISD::VPERMV3:
3843     return true;
3844   }
3845 }
3846
3847 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3848                                     SDValue V1, unsigned TargetMask,
3849                                     SelectionDAG &DAG) {
3850   switch(Opc) {
3851   default: llvm_unreachable("Unknown x86 shuffle node");
3852   case X86ISD::PSHUFD:
3853   case X86ISD::PSHUFHW:
3854   case X86ISD::PSHUFLW:
3855   case X86ISD::VPERMILPI:
3856   case X86ISD::VPERMI:
3857     return DAG.getNode(Opc, dl, VT, V1,
3858                        DAG.getConstant(TargetMask, dl, MVT::i8));
3859   }
3860 }
3861
3862 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3863                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3864   switch(Opc) {
3865   default: llvm_unreachable("Unknown x86 shuffle node");
3866   case X86ISD::MOVLHPS:
3867   case X86ISD::MOVLHPD:
3868   case X86ISD::MOVHLPS:
3869   case X86ISD::MOVLPS:
3870   case X86ISD::MOVLPD:
3871   case X86ISD::MOVSS:
3872   case X86ISD::MOVSD:
3873   case X86ISD::UNPCKL:
3874   case X86ISD::UNPCKH:
3875     return DAG.getNode(Opc, dl, VT, V1, V2);
3876   }
3877 }
3878
3879 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3880   MachineFunction &MF = DAG.getMachineFunction();
3881   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3882   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3883   int ReturnAddrIndex = FuncInfo->getRAIndex();
3884
3885   if (ReturnAddrIndex == 0) {
3886     // Set up a frame object for the return address.
3887     unsigned SlotSize = RegInfo->getSlotSize();
3888     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3889                                                            -(int64_t)SlotSize,
3890                                                            false);
3891     FuncInfo->setRAIndex(ReturnAddrIndex);
3892   }
3893
3894   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3895 }
3896
3897 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3898                                        bool hasSymbolicDisplacement) {
3899   // Offset should fit into 32 bit immediate field.
3900   if (!isInt<32>(Offset))
3901     return false;
3902
3903   // If we don't have a symbolic displacement - we don't have any extra
3904   // restrictions.
3905   if (!hasSymbolicDisplacement)
3906     return true;
3907
3908   // FIXME: Some tweaks might be needed for medium code model.
3909   if (M != CodeModel::Small && M != CodeModel::Kernel)
3910     return false;
3911
3912   // For small code model we assume that latest object is 16MB before end of 31
3913   // bits boundary. We may also accept pretty large negative constants knowing
3914   // that all objects are in the positive half of address space.
3915   if (M == CodeModel::Small && Offset < 16*1024*1024)
3916     return true;
3917
3918   // For kernel code model we know that all object resist in the negative half
3919   // of 32bits address space. We may not accept negative offsets, since they may
3920   // be just off and we may accept pretty large positive ones.
3921   if (M == CodeModel::Kernel && Offset >= 0)
3922     return true;
3923
3924   return false;
3925 }
3926
3927 /// Determines whether the callee is required to pop its own arguments.
3928 /// Callee pop is necessary to support tail calls.
3929 bool X86::isCalleePop(CallingConv::ID CallingConv,
3930                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3931   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3932   // can guarantee TCO.
3933   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3934     return true;
3935
3936   switch (CallingConv) {
3937   default:
3938     return false;
3939   case CallingConv::X86_StdCall:
3940   case CallingConv::X86_FastCall:
3941   case CallingConv::X86_ThisCall:
3942   case CallingConv::X86_VectorCall:
3943     return !is64Bit;
3944   }
3945 }
3946
3947 /// \brief Return true if the condition is an unsigned comparison operation.
3948 static bool isX86CCUnsigned(unsigned X86CC) {
3949   switch (X86CC) {
3950   default: llvm_unreachable("Invalid integer condition!");
3951   case X86::COND_E:     return true;
3952   case X86::COND_G:     return false;
3953   case X86::COND_GE:    return false;
3954   case X86::COND_L:     return false;
3955   case X86::COND_LE:    return false;
3956   case X86::COND_NE:    return true;
3957   case X86::COND_B:     return true;
3958   case X86::COND_A:     return true;
3959   case X86::COND_BE:    return true;
3960   case X86::COND_AE:    return true;
3961   }
3962 }
3963
3964 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
3965   switch (SetCCOpcode) {
3966   default: llvm_unreachable("Invalid integer condition!");
3967   case ISD::SETEQ:  return X86::COND_E;
3968   case ISD::SETGT:  return X86::COND_G;
3969   case ISD::SETGE:  return X86::COND_GE;
3970   case ISD::SETLT:  return X86::COND_L;
3971   case ISD::SETLE:  return X86::COND_LE;
3972   case ISD::SETNE:  return X86::COND_NE;
3973   case ISD::SETULT: return X86::COND_B;
3974   case ISD::SETUGT: return X86::COND_A;
3975   case ISD::SETULE: return X86::COND_BE;
3976   case ISD::SETUGE: return X86::COND_AE;
3977   }
3978 }
3979
3980 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3981 /// condition code, returning the condition code and the LHS/RHS of the
3982 /// comparison to make.
3983 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3984                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3985   if (!isFP) {
3986     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3987       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3988         // X > -1   -> X == 0, jump !sign.
3989         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3990         return X86::COND_NS;
3991       }
3992       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3993         // X < 0   -> X == 0, jump on sign.
3994         return X86::COND_S;
3995       }
3996       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3997         // X < 1   -> X <= 0
3998         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3999         return X86::COND_LE;
4000       }
4001     }
4002
4003     return TranslateIntegerX86CC(SetCCOpcode);
4004   }
4005
4006   // First determine if it is required or is profitable to flip the operands.
4007
4008   // If LHS is a foldable load, but RHS is not, flip the condition.
4009   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4010       !ISD::isNON_EXTLoad(RHS.getNode())) {
4011     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4012     std::swap(LHS, RHS);
4013   }
4014
4015   switch (SetCCOpcode) {
4016   default: break;
4017   case ISD::SETOLT:
4018   case ISD::SETOLE:
4019   case ISD::SETUGT:
4020   case ISD::SETUGE:
4021     std::swap(LHS, RHS);
4022     break;
4023   }
4024
4025   // On a floating point condition, the flags are set as follows:
4026   // ZF  PF  CF   op
4027   //  0 | 0 | 0 | X > Y
4028   //  0 | 0 | 1 | X < Y
4029   //  1 | 0 | 0 | X == Y
4030   //  1 | 1 | 1 | unordered
4031   switch (SetCCOpcode) {
4032   default: llvm_unreachable("Condcode should be pre-legalized away");
4033   case ISD::SETUEQ:
4034   case ISD::SETEQ:   return X86::COND_E;
4035   case ISD::SETOLT:              // flipped
4036   case ISD::SETOGT:
4037   case ISD::SETGT:   return X86::COND_A;
4038   case ISD::SETOLE:              // flipped
4039   case ISD::SETOGE:
4040   case ISD::SETGE:   return X86::COND_AE;
4041   case ISD::SETUGT:              // flipped
4042   case ISD::SETULT:
4043   case ISD::SETLT:   return X86::COND_B;
4044   case ISD::SETUGE:              // flipped
4045   case ISD::SETULE:
4046   case ISD::SETLE:   return X86::COND_BE;
4047   case ISD::SETONE:
4048   case ISD::SETNE:   return X86::COND_NE;
4049   case ISD::SETUO:   return X86::COND_P;
4050   case ISD::SETO:    return X86::COND_NP;
4051   case ISD::SETOEQ:
4052   case ISD::SETUNE:  return X86::COND_INVALID;
4053   }
4054 }
4055
4056 /// Is there a floating point cmov for the specific X86 condition code?
4057 /// Current x86 isa includes the following FP cmov instructions:
4058 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4059 static bool hasFPCMov(unsigned X86CC) {
4060   switch (X86CC) {
4061   default:
4062     return false;
4063   case X86::COND_B:
4064   case X86::COND_BE:
4065   case X86::COND_E:
4066   case X86::COND_P:
4067   case X86::COND_A:
4068   case X86::COND_AE:
4069   case X86::COND_NE:
4070   case X86::COND_NP:
4071     return true;
4072   }
4073 }
4074
4075 /// Returns true if the target can instruction select the
4076 /// specified FP immediate natively. If false, the legalizer will
4077 /// materialize the FP immediate as a load from a constant pool.
4078 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4079   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4080     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4081       return true;
4082   }
4083   return false;
4084 }
4085
4086 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4087                                               ISD::LoadExtType ExtTy,
4088                                               EVT NewVT) const {
4089   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4090   // relocation target a movq or addq instruction: don't let the load shrink.
4091   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4092   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4093     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4094       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4095   return true;
4096 }
4097
4098 /// \brief Returns true if it is beneficial to convert a load of a constant
4099 /// to just the constant itself.
4100 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4101                                                           Type *Ty) const {
4102   assert(Ty->isIntegerTy());
4103
4104   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4105   if (BitSize == 0 || BitSize > 64)
4106     return false;
4107   return true;
4108 }
4109
4110 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4111                                                 unsigned Index) const {
4112   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4113     return false;
4114
4115   return (Index == 0 || Index == ResVT.getVectorNumElements());
4116 }
4117
4118 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4119   // Speculate cttz only if we can directly use TZCNT.
4120   return Subtarget->hasBMI();
4121 }
4122
4123 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4124   // Speculate ctlz only if we can directly use LZCNT.
4125   return Subtarget->hasLZCNT();
4126 }
4127
4128 /// Return true if every element in Mask, beginning
4129 /// from position Pos and ending in Pos+Size is undef.
4130 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4131   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4132     if (0 <= Mask[i])
4133       return false;
4134   return true;
4135 }
4136
4137 /// Return true if Val is undef or if its value falls within the
4138 /// specified range (L, H].
4139 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4140   return (Val < 0) || (Val >= Low && Val < Hi);
4141 }
4142
4143 /// Val is either less than zero (undef) or equal to the specified value.
4144 static bool isUndefOrEqual(int Val, int CmpVal) {
4145   return (Val < 0 || Val == CmpVal);
4146 }
4147
4148 /// Return true if every element in Mask, beginning
4149 /// from position Pos and ending in Pos+Size, falls within the specified
4150 /// sequential range (Low, Low+Size]. or is undef.
4151 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4152                                        unsigned Pos, unsigned Size, int Low) {
4153   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4154     if (!isUndefOrEqual(Mask[i], Low))
4155       return false;
4156   return true;
4157 }
4158
4159 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4160 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4161 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4162   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4163   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4164     return false;
4165
4166   // The index should be aligned on a vecWidth-bit boundary.
4167   uint64_t Index =
4168     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4169
4170   MVT VT = N->getSimpleValueType(0);
4171   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4172   bool Result = (Index * ElSize) % vecWidth == 0;
4173
4174   return Result;
4175 }
4176
4177 /// Return true if the specified INSERT_SUBVECTOR
4178 /// operand specifies a subvector insert that is suitable for input to
4179 /// insertion of 128 or 256-bit subvectors
4180 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4181   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4182   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4183     return false;
4184   // The index should be aligned on a vecWidth-bit boundary.
4185   uint64_t Index =
4186     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4187
4188   MVT VT = N->getSimpleValueType(0);
4189   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4190   bool Result = (Index * ElSize) % vecWidth == 0;
4191
4192   return Result;
4193 }
4194
4195 bool X86::isVINSERT128Index(SDNode *N) {
4196   return isVINSERTIndex(N, 128);
4197 }
4198
4199 bool X86::isVINSERT256Index(SDNode *N) {
4200   return isVINSERTIndex(N, 256);
4201 }
4202
4203 bool X86::isVEXTRACT128Index(SDNode *N) {
4204   return isVEXTRACTIndex(N, 128);
4205 }
4206
4207 bool X86::isVEXTRACT256Index(SDNode *N) {
4208   return isVEXTRACTIndex(N, 256);
4209 }
4210
4211 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4212   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4213   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4214          "Illegal extract subvector for VEXTRACT");
4215
4216   uint64_t Index =
4217     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4218
4219   MVT VecVT = N->getOperand(0).getSimpleValueType();
4220   MVT ElVT = VecVT.getVectorElementType();
4221
4222   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4223   return Index / NumElemsPerChunk;
4224 }
4225
4226 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4227   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4228   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4229          "Illegal insert subvector for VINSERT");
4230
4231   uint64_t Index =
4232     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4233
4234   MVT VecVT = N->getSimpleValueType(0);
4235   MVT ElVT = VecVT.getVectorElementType();
4236
4237   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4238   return Index / NumElemsPerChunk;
4239 }
4240
4241 /// Return the appropriate immediate to extract the specified
4242 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4243 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4244   return getExtractVEXTRACTImmediate(N, 128);
4245 }
4246
4247 /// Return the appropriate immediate to extract the specified
4248 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4249 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4250   return getExtractVEXTRACTImmediate(N, 256);
4251 }
4252
4253 /// Return the appropriate immediate to insert at the specified
4254 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4255 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4256   return getInsertVINSERTImmediate(N, 128);
4257 }
4258
4259 /// Return the appropriate immediate to insert at the specified
4260 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4261 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4262   return getInsertVINSERTImmediate(N, 256);
4263 }
4264
4265 /// Returns true if V is a constant integer zero.
4266 static bool isZero(SDValue V) {
4267   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4268   return C && C->isNullValue();
4269 }
4270
4271 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4272 bool X86::isZeroNode(SDValue Elt) {
4273   if (isZero(Elt))
4274     return true;
4275   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4276     return CFP->getValueAPF().isPosZero();
4277   return false;
4278 }
4279
4280 // Build a vector of constants
4281 // Use an UNDEF node if MaskElt == -1.
4282 // Spilt 64-bit constants in the 32-bit mode.
4283 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4284                               SelectionDAG &DAG,
4285                               SDLoc dl, bool IsMask = false) {
4286
4287   SmallVector<SDValue, 32>  Ops;
4288   bool Split = false;
4289
4290   MVT ConstVecVT = VT;
4291   unsigned NumElts = VT.getVectorNumElements();
4292   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4293   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4294     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4295     Split = true;
4296   }
4297
4298   MVT EltVT = ConstVecVT.getVectorElementType();
4299   for (unsigned i = 0; i < NumElts; ++i) {
4300     bool IsUndef = Values[i] < 0 && IsMask;
4301     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4302       DAG.getConstant(Values[i], dl, EltVT);
4303     Ops.push_back(OpNode);
4304     if (Split)
4305       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4306                     DAG.getConstant(0, dl, EltVT));
4307   }
4308   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4309   if (Split)
4310     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4311   return ConstsNode;
4312 }
4313
4314 /// Returns a vector of specified type with all zero elements.
4315 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4316                              SelectionDAG &DAG, SDLoc dl) {
4317   assert(VT.isVector() && "Expected a vector type");
4318
4319   // Always build SSE zero vectors as <4 x i32> bitcasted
4320   // to their dest type. This ensures they get CSE'd.
4321   SDValue Vec;
4322   if (VT.is128BitVector()) {  // SSE
4323     if (Subtarget->hasSSE2()) {  // SSE2
4324       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4325       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4326     } else { // SSE1
4327       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4328       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4329     }
4330   } else if (VT.is256BitVector()) { // AVX
4331     if (Subtarget->hasInt256()) { // AVX2
4332       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4333       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4335     } else {
4336       // 256-bit logic and arithmetic instructions in AVX are all
4337       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4338       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4339       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4340       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4341     }
4342   } else if (VT.is512BitVector()) { // AVX-512
4343       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4344       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4345                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4346       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4347   } else if (VT.getVectorElementType() == MVT::i1) {
4348
4349     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4350             && "Unexpected vector type");
4351     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4352             && "Unexpected vector type");
4353     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4354     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4355     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4356   } else
4357     llvm_unreachable("Unexpected vector type");
4358
4359   return DAG.getBitcast(VT, Vec);
4360 }
4361
4362 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4363                                 SelectionDAG &DAG, SDLoc dl,
4364                                 unsigned vectorWidth) {
4365   assert((vectorWidth == 128 || vectorWidth == 256) &&
4366          "Unsupported vector width");
4367   EVT VT = Vec.getValueType();
4368   EVT ElVT = VT.getVectorElementType();
4369   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4370   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4371                                   VT.getVectorNumElements()/Factor);
4372
4373   // Extract from UNDEF is UNDEF.
4374   if (Vec.getOpcode() == ISD::UNDEF)
4375     return DAG.getUNDEF(ResultVT);
4376
4377   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4378   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4379   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4380
4381   // This is the index of the first element of the vectorWidth-bit chunk
4382   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4383   IdxVal &= ~(ElemsPerChunk - 1);
4384
4385   // If the input is a buildvector just emit a smaller one.
4386   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4387     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4388                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4389
4390   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4391   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4392 }
4393
4394 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4395 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4396 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4397 /// instructions or a simple subregister reference. Idx is an index in the
4398 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4399 /// lowering EXTRACT_VECTOR_ELT operations easier.
4400 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4401                                    SelectionDAG &DAG, SDLoc dl) {
4402   assert((Vec.getValueType().is256BitVector() ||
4403           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4404   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4405 }
4406
4407 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4408 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4409                                    SelectionDAG &DAG, SDLoc dl) {
4410   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4411   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4412 }
4413
4414 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4415                                unsigned IdxVal, SelectionDAG &DAG,
4416                                SDLoc dl, unsigned vectorWidth) {
4417   assert((vectorWidth == 128 || vectorWidth == 256) &&
4418          "Unsupported vector width");
4419   // Inserting UNDEF is Result
4420   if (Vec.getOpcode() == ISD::UNDEF)
4421     return Result;
4422   EVT VT = Vec.getValueType();
4423   EVT ElVT = VT.getVectorElementType();
4424   EVT ResultVT = Result.getValueType();
4425
4426   // Insert the relevant vectorWidth bits.
4427   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4428   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4429
4430   // This is the index of the first element of the vectorWidth-bit chunk
4431   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4432   IdxVal &= ~(ElemsPerChunk - 1);
4433
4434   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4435   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4436 }
4437
4438 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4439 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4440 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4441 /// simple superregister reference.  Idx is an index in the 128 bits
4442 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4443 /// lowering INSERT_VECTOR_ELT operations easier.
4444 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4445                                   SelectionDAG &DAG, SDLoc dl) {
4446   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4447
4448   // For insertion into the zero index (low half) of a 256-bit vector, it is
4449   // more efficient to generate a blend with immediate instead of an insert*128.
4450   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4451   // extend the subvector to the size of the result vector. Make sure that
4452   // we are not recursing on that node by checking for undef here.
4453   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4454       Result.getOpcode() != ISD::UNDEF) {
4455     EVT ResultVT = Result.getValueType();
4456     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4457     SDValue Undef = DAG.getUNDEF(ResultVT);
4458     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4459                                  Vec, ZeroIndex);
4460
4461     // The blend instruction, and therefore its mask, depend on the data type.
4462     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4463     if (ScalarType.isFloatingPoint()) {
4464       // Choose either vblendps (float) or vblendpd (double).
4465       unsigned ScalarSize = ScalarType.getSizeInBits();
4466       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4467       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4468       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4469       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4470     }
4471
4472     const X86Subtarget &Subtarget =
4473     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4474
4475     // AVX2 is needed for 256-bit integer blend support.
4476     // Integers must be cast to 32-bit because there is only vpblendd;
4477     // vpblendw can't be used for this because it has a handicapped mask.
4478
4479     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4480     // is still more efficient than using the wrong domain vinsertf128 that
4481     // will be created by InsertSubVector().
4482     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4483
4484     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4485     Vec256 = DAG.getBitcast(CastVT, Vec256);
4486     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4487     return DAG.getBitcast(ResultVT, Vec256);
4488   }
4489
4490   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4491 }
4492
4493 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4494                                   SelectionDAG &DAG, SDLoc dl) {
4495   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4496   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4497 }
4498
4499 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4500 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4501 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4502 /// large BUILD_VECTORS.
4503 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4504                                    unsigned NumElems, SelectionDAG &DAG,
4505                                    SDLoc dl) {
4506   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4507   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4508 }
4509
4510 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4511                                    unsigned NumElems, SelectionDAG &DAG,
4512                                    SDLoc dl) {
4513   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4514   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4515 }
4516
4517 /// Returns a vector of specified type with all bits set.
4518 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4519 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4520 /// Then bitcast to their original type, ensuring they get CSE'd.
4521 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4522                              SelectionDAG &DAG, SDLoc dl) {
4523   assert(VT.isVector() && "Expected a vector type");
4524
4525   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4526   SDValue Vec;
4527   if (VT.is512BitVector()) {
4528     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4529                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4530     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4531   } else if (VT.is256BitVector()) {
4532     if (Subtarget->hasInt256()) { // AVX2
4533       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4534       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4535     } else { // AVX
4536       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4537       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4538     }
4539   } else if (VT.is128BitVector()) {
4540     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4541   } else
4542     llvm_unreachable("Unexpected vector type");
4543
4544   return DAG.getBitcast(VT, Vec);
4545 }
4546
4547 /// Returns a vector_shuffle node for an unpackl operation.
4548 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4549                           SDValue V2) {
4550   unsigned NumElems = VT.getVectorNumElements();
4551   SmallVector<int, 8> Mask;
4552   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4553     Mask.push_back(i);
4554     Mask.push_back(i + NumElems);
4555   }
4556   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4557 }
4558
4559 /// Returns a vector_shuffle node for an unpackh operation.
4560 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4561                           SDValue V2) {
4562   unsigned NumElems = VT.getVectorNumElements();
4563   SmallVector<int, 8> Mask;
4564   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4565     Mask.push_back(i + Half);
4566     Mask.push_back(i + NumElems + Half);
4567   }
4568   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4569 }
4570
4571 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4572 /// This produces a shuffle where the low element of V2 is swizzled into the
4573 /// zero/undef vector, landing at element Idx.
4574 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4575 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4576                                            bool IsZero,
4577                                            const X86Subtarget *Subtarget,
4578                                            SelectionDAG &DAG) {
4579   MVT VT = V2.getSimpleValueType();
4580   SDValue V1 = IsZero
4581     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4582   unsigned NumElems = VT.getVectorNumElements();
4583   SmallVector<int, 16> MaskVec;
4584   for (unsigned i = 0; i != NumElems; ++i)
4585     // If this is the insertion idx, put the low elt of V2 here.
4586     MaskVec.push_back(i == Idx ? NumElems : i);
4587   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4588 }
4589
4590 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4591 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4592 /// uses one source. Note that this will set IsUnary for shuffles which use a
4593 /// single input multiple times, and in those cases it will
4594 /// adjust the mask to only have indices within that single input.
4595 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4596 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4597                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4598   unsigned NumElems = VT.getVectorNumElements();
4599   SDValue ImmN;
4600
4601   IsUnary = false;
4602   bool IsFakeUnary = false;
4603   switch(N->getOpcode()) {
4604   case X86ISD::BLENDI:
4605     ImmN = N->getOperand(N->getNumOperands()-1);
4606     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4607     break;
4608   case X86ISD::SHUFP:
4609     ImmN = N->getOperand(N->getNumOperands()-1);
4610     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4611     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4612     break;
4613   case X86ISD::UNPCKH:
4614     DecodeUNPCKHMask(VT, Mask);
4615     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4616     break;
4617   case X86ISD::UNPCKL:
4618     DecodeUNPCKLMask(VT, Mask);
4619     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4620     break;
4621   case X86ISD::MOVHLPS:
4622     DecodeMOVHLPSMask(NumElems, Mask);
4623     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4624     break;
4625   case X86ISD::MOVLHPS:
4626     DecodeMOVLHPSMask(NumElems, Mask);
4627     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4628     break;
4629   case X86ISD::PALIGNR:
4630     ImmN = N->getOperand(N->getNumOperands()-1);
4631     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4632     break;
4633   case X86ISD::PSHUFD:
4634   case X86ISD::VPERMILPI:
4635     ImmN = N->getOperand(N->getNumOperands()-1);
4636     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4637     IsUnary = true;
4638     break;
4639   case X86ISD::PSHUFHW:
4640     ImmN = N->getOperand(N->getNumOperands()-1);
4641     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4642     IsUnary = true;
4643     break;
4644   case X86ISD::PSHUFLW:
4645     ImmN = N->getOperand(N->getNumOperands()-1);
4646     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4647     IsUnary = true;
4648     break;
4649   case X86ISD::PSHUFB: {
4650     IsUnary = true;
4651     SDValue MaskNode = N->getOperand(1);
4652     while (MaskNode->getOpcode() == ISD::BITCAST)
4653       MaskNode = MaskNode->getOperand(0);
4654
4655     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4656       // If we have a build-vector, then things are easy.
4657       MVT VT = MaskNode.getSimpleValueType();
4658       assert(VT.isVector() &&
4659              "Can't produce a non-vector with a build_vector!");
4660       if (!VT.isInteger())
4661         return false;
4662
4663       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4664
4665       SmallVector<uint64_t, 32> RawMask;
4666       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4667         SDValue Op = MaskNode->getOperand(i);
4668         if (Op->getOpcode() == ISD::UNDEF) {
4669           RawMask.push_back((uint64_t)SM_SentinelUndef);
4670           continue;
4671         }
4672         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4673         if (!CN)
4674           return false;
4675         APInt MaskElement = CN->getAPIntValue();
4676
4677         // We now have to decode the element which could be any integer size and
4678         // extract each byte of it.
4679         for (int j = 0; j < NumBytesPerElement; ++j) {
4680           // Note that this is x86 and so always little endian: the low byte is
4681           // the first byte of the mask.
4682           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4683           MaskElement = MaskElement.lshr(8);
4684         }
4685       }
4686       DecodePSHUFBMask(RawMask, Mask);
4687       break;
4688     }
4689
4690     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4691     if (!MaskLoad)
4692       return false;
4693
4694     SDValue Ptr = MaskLoad->getBasePtr();
4695     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4696         Ptr->getOpcode() == X86ISD::WrapperRIP)
4697       Ptr = Ptr->getOperand(0);
4698
4699     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4700     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4701       return false;
4702
4703     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4704       DecodePSHUFBMask(C, Mask);
4705       if (Mask.empty())
4706         return false;
4707       break;
4708     }
4709
4710     return false;
4711   }
4712   case X86ISD::VPERMI:
4713     ImmN = N->getOperand(N->getNumOperands()-1);
4714     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4715     IsUnary = true;
4716     break;
4717   case X86ISD::MOVSS:
4718   case X86ISD::MOVSD:
4719     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4720     break;
4721   case X86ISD::VPERM2X128:
4722     ImmN = N->getOperand(N->getNumOperands()-1);
4723     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4724     if (Mask.empty()) return false;
4725     // Mask only contains negative index if an element is zero.
4726     if (std::any_of(Mask.begin(), Mask.end(),
4727                     [](int M){ return M == SM_SentinelZero; }))
4728       return false;
4729     break;
4730   case X86ISD::MOVSLDUP:
4731     DecodeMOVSLDUPMask(VT, Mask);
4732     IsUnary = true;
4733     break;
4734   case X86ISD::MOVSHDUP:
4735     DecodeMOVSHDUPMask(VT, Mask);
4736     IsUnary = true;
4737     break;
4738   case X86ISD::MOVDDUP:
4739     DecodeMOVDDUPMask(VT, Mask);
4740     IsUnary = true;
4741     break;
4742   case X86ISD::MOVLHPD:
4743   case X86ISD::MOVLPD:
4744   case X86ISD::MOVLPS:
4745     // Not yet implemented
4746     return false;
4747   case X86ISD::VPERMV: {
4748     IsUnary = true;
4749     SDValue MaskNode = N->getOperand(0);
4750     while (MaskNode->getOpcode() == ISD::BITCAST)
4751       MaskNode = MaskNode->getOperand(0);
4752
4753     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4754     SmallVector<uint64_t, 32> RawMask;
4755     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4756       // If we have a build-vector, then things are easy.
4757       assert(MaskNode.getSimpleValueType().isInteger() &&
4758              MaskNode.getSimpleValueType().getVectorNumElements() ==
4759              VT.getVectorNumElements());
4760
4761       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4762         SDValue Op = MaskNode->getOperand(i);
4763         if (Op->getOpcode() == ISD::UNDEF)
4764           RawMask.push_back((uint64_t)SM_SentinelUndef);
4765         else if (isa<ConstantSDNode>(Op)) {
4766           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4767           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4768         } else
4769           return false;
4770       }
4771       DecodeVPERMVMask(RawMask, Mask);
4772       break;
4773     }
4774     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4775       unsigned NumEltsInMask = MaskNode->getNumOperands();
4776       MaskNode = MaskNode->getOperand(0);
4777       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4778       if (CN) {
4779         APInt MaskEltValue = CN->getAPIntValue();
4780         for (unsigned i = 0; i < NumEltsInMask; ++i)
4781           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4782         DecodeVPERMVMask(RawMask, Mask);
4783         break;
4784       }
4785       // It may be a scalar load
4786     }
4787
4788     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4789     if (!MaskLoad)
4790       return false;
4791
4792     SDValue Ptr = MaskLoad->getBasePtr();
4793     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4794         Ptr->getOpcode() == X86ISD::WrapperRIP)
4795       Ptr = Ptr->getOperand(0);
4796
4797     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4798     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4799       return false;
4800
4801     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4802     if (C) {
4803       DecodeVPERMVMask(C, VT, Mask);
4804       if (Mask.empty())
4805         return false;
4806       break;
4807     }
4808     return false;
4809   }
4810   case X86ISD::VPERMV3: {
4811     IsUnary = false;
4812     SDValue MaskNode = N->getOperand(1);
4813     while (MaskNode->getOpcode() == ISD::BITCAST)
4814       MaskNode = MaskNode->getOperand(1);
4815
4816     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4817       // If we have a build-vector, then things are easy.
4818       assert(MaskNode.getSimpleValueType().isInteger() &&
4819              MaskNode.getSimpleValueType().getVectorNumElements() ==
4820              VT.getVectorNumElements());
4821
4822       SmallVector<uint64_t, 32> RawMask;
4823       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4824
4825       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4826         SDValue Op = MaskNode->getOperand(i);
4827         if (Op->getOpcode() == ISD::UNDEF)
4828           RawMask.push_back((uint64_t)SM_SentinelUndef);
4829         else {
4830           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4831           if (!CN)
4832             return false;
4833           APInt MaskElement = CN->getAPIntValue();
4834           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4835         }
4836       }
4837       DecodeVPERMV3Mask(RawMask, Mask);
4838       break;
4839     }
4840
4841     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4842     if (!MaskLoad)
4843       return false;
4844
4845     SDValue Ptr = MaskLoad->getBasePtr();
4846     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4847         Ptr->getOpcode() == X86ISD::WrapperRIP)
4848       Ptr = Ptr->getOperand(0);
4849
4850     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4851     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4852       return false;
4853
4854     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4855     if (C) {
4856       DecodeVPERMV3Mask(C, VT, Mask);
4857       if (Mask.empty())
4858         return false;
4859       break;
4860     }
4861     return false;
4862   }
4863   default: llvm_unreachable("unknown target shuffle node");
4864   }
4865
4866   // If we have a fake unary shuffle, the shuffle mask is spread across two
4867   // inputs that are actually the same node. Re-map the mask to always point
4868   // into the first input.
4869   if (IsFakeUnary)
4870     for (int &M : Mask)
4871       if (M >= (int)Mask.size())
4872         M -= Mask.size();
4873
4874   return true;
4875 }
4876
4877 /// Returns the scalar element that will make up the ith
4878 /// element of the result of the vector shuffle.
4879 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4880                                    unsigned Depth) {
4881   if (Depth == 6)
4882     return SDValue();  // Limit search depth.
4883
4884   SDValue V = SDValue(N, 0);
4885   EVT VT = V.getValueType();
4886   unsigned Opcode = V.getOpcode();
4887
4888   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4889   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4890     int Elt = SV->getMaskElt(Index);
4891
4892     if (Elt < 0)
4893       return DAG.getUNDEF(VT.getVectorElementType());
4894
4895     unsigned NumElems = VT.getVectorNumElements();
4896     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4897                                          : SV->getOperand(1);
4898     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4899   }
4900
4901   // Recurse into target specific vector shuffles to find scalars.
4902   if (isTargetShuffle(Opcode)) {
4903     MVT ShufVT = V.getSimpleValueType();
4904     unsigned NumElems = ShufVT.getVectorNumElements();
4905     SmallVector<int, 16> ShuffleMask;
4906     bool IsUnary;
4907
4908     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4909       return SDValue();
4910
4911     int Elt = ShuffleMask[Index];
4912     if (Elt < 0)
4913       return DAG.getUNDEF(ShufVT.getVectorElementType());
4914
4915     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4916                                          : N->getOperand(1);
4917     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4918                                Depth+1);
4919   }
4920
4921   // Actual nodes that may contain scalar elements
4922   if (Opcode == ISD::BITCAST) {
4923     V = V.getOperand(0);
4924     EVT SrcVT = V.getValueType();
4925     unsigned NumElems = VT.getVectorNumElements();
4926
4927     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4928       return SDValue();
4929   }
4930
4931   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4932     return (Index == 0) ? V.getOperand(0)
4933                         : DAG.getUNDEF(VT.getVectorElementType());
4934
4935   if (V.getOpcode() == ISD::BUILD_VECTOR)
4936     return V.getOperand(Index);
4937
4938   return SDValue();
4939 }
4940
4941 /// Custom lower build_vector of v16i8.
4942 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4943                                        unsigned NumNonZero, unsigned NumZero,
4944                                        SelectionDAG &DAG,
4945                                        const X86Subtarget* Subtarget,
4946                                        const TargetLowering &TLI) {
4947   if (NumNonZero > 8)
4948     return SDValue();
4949
4950   SDLoc dl(Op);
4951   SDValue V;
4952   bool First = true;
4953
4954   // SSE4.1 - use PINSRB to insert each byte directly.
4955   if (Subtarget->hasSSE41()) {
4956     for (unsigned i = 0; i < 16; ++i) {
4957       bool isNonZero = (NonZeros & (1 << i)) != 0;
4958       if (isNonZero) {
4959         if (First) {
4960           if (NumZero)
4961             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4962           else
4963             V = DAG.getUNDEF(MVT::v16i8);
4964           First = false;
4965         }
4966         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4967                         MVT::v16i8, V, Op.getOperand(i),
4968                         DAG.getIntPtrConstant(i, dl));
4969       }
4970     }
4971
4972     return V;
4973   }
4974
4975   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4976   for (unsigned i = 0; i < 16; ++i) {
4977     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4978     if (ThisIsNonZero && First) {
4979       if (NumZero)
4980         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4981       else
4982         V = DAG.getUNDEF(MVT::v8i16);
4983       First = false;
4984     }
4985
4986     if ((i & 1) != 0) {
4987       SDValue ThisElt, LastElt;
4988       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4989       if (LastIsNonZero) {
4990         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4991                               MVT::i16, Op.getOperand(i-1));
4992       }
4993       if (ThisIsNonZero) {
4994         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4995         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4996                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4997         if (LastIsNonZero)
4998           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4999       } else
5000         ThisElt = LastElt;
5001
5002       if (ThisElt.getNode())
5003         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5004                         DAG.getIntPtrConstant(i/2, dl));
5005     }
5006   }
5007
5008   return DAG.getBitcast(MVT::v16i8, V);
5009 }
5010
5011 /// Custom lower build_vector of v8i16.
5012 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5013                                      unsigned NumNonZero, unsigned NumZero,
5014                                      SelectionDAG &DAG,
5015                                      const X86Subtarget* Subtarget,
5016                                      const TargetLowering &TLI) {
5017   if (NumNonZero > 4)
5018     return SDValue();
5019
5020   SDLoc dl(Op);
5021   SDValue V;
5022   bool First = true;
5023   for (unsigned i = 0; i < 8; ++i) {
5024     bool isNonZero = (NonZeros & (1 << i)) != 0;
5025     if (isNonZero) {
5026       if (First) {
5027         if (NumZero)
5028           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5029         else
5030           V = DAG.getUNDEF(MVT::v8i16);
5031         First = false;
5032       }
5033       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5034                       MVT::v8i16, V, Op.getOperand(i),
5035                       DAG.getIntPtrConstant(i, dl));
5036     }
5037   }
5038
5039   return V;
5040 }
5041
5042 /// Custom lower build_vector of v4i32 or v4f32.
5043 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5044                                      const X86Subtarget *Subtarget,
5045                                      const TargetLowering &TLI) {
5046   // Find all zeroable elements.
5047   std::bitset<4> Zeroable;
5048   for (int i=0; i < 4; ++i) {
5049     SDValue Elt = Op->getOperand(i);
5050     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5051   }
5052   assert(Zeroable.size() - Zeroable.count() > 1 &&
5053          "We expect at least two non-zero elements!");
5054
5055   // We only know how to deal with build_vector nodes where elements are either
5056   // zeroable or extract_vector_elt with constant index.
5057   SDValue FirstNonZero;
5058   unsigned FirstNonZeroIdx;
5059   for (unsigned i=0; i < 4; ++i) {
5060     if (Zeroable[i])
5061       continue;
5062     SDValue Elt = Op->getOperand(i);
5063     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5064         !isa<ConstantSDNode>(Elt.getOperand(1)))
5065       return SDValue();
5066     // Make sure that this node is extracting from a 128-bit vector.
5067     MVT VT = Elt.getOperand(0).getSimpleValueType();
5068     if (!VT.is128BitVector())
5069       return SDValue();
5070     if (!FirstNonZero.getNode()) {
5071       FirstNonZero = Elt;
5072       FirstNonZeroIdx = i;
5073     }
5074   }
5075
5076   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5077   SDValue V1 = FirstNonZero.getOperand(0);
5078   MVT VT = V1.getSimpleValueType();
5079
5080   // See if this build_vector can be lowered as a blend with zero.
5081   SDValue Elt;
5082   unsigned EltMaskIdx, EltIdx;
5083   int Mask[4];
5084   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5085     if (Zeroable[EltIdx]) {
5086       // The zero vector will be on the right hand side.
5087       Mask[EltIdx] = EltIdx+4;
5088       continue;
5089     }
5090
5091     Elt = Op->getOperand(EltIdx);
5092     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5093     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5094     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5095       break;
5096     Mask[EltIdx] = EltIdx;
5097   }
5098
5099   if (EltIdx == 4) {
5100     // Let the shuffle legalizer deal with blend operations.
5101     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5102     if (V1.getSimpleValueType() != VT)
5103       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5104     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5105   }
5106
5107   // See if we can lower this build_vector to a INSERTPS.
5108   if (!Subtarget->hasSSE41())
5109     return SDValue();
5110
5111   SDValue V2 = Elt.getOperand(0);
5112   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5113     V1 = SDValue();
5114
5115   bool CanFold = true;
5116   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5117     if (Zeroable[i])
5118       continue;
5119
5120     SDValue Current = Op->getOperand(i);
5121     SDValue SrcVector = Current->getOperand(0);
5122     if (!V1.getNode())
5123       V1 = SrcVector;
5124     CanFold = SrcVector == V1 &&
5125       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5126   }
5127
5128   if (!CanFold)
5129     return SDValue();
5130
5131   assert(V1.getNode() && "Expected at least two non-zero elements!");
5132   if (V1.getSimpleValueType() != MVT::v4f32)
5133     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5134   if (V2.getSimpleValueType() != MVT::v4f32)
5135     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5136
5137   // Ok, we can emit an INSERTPS instruction.
5138   unsigned ZMask = Zeroable.to_ulong();
5139
5140   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5141   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5142   SDLoc DL(Op);
5143   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5144                                DAG.getIntPtrConstant(InsertPSMask, DL));
5145   return DAG.getBitcast(VT, Result);
5146 }
5147
5148 /// Return a vector logical shift node.
5149 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5150                          unsigned NumBits, SelectionDAG &DAG,
5151                          const TargetLowering &TLI, SDLoc dl) {
5152   assert(VT.is128BitVector() && "Unknown type for VShift");
5153   MVT ShVT = MVT::v2i64;
5154   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5155   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5156   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5157   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5158   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5159   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5160 }
5161
5162 static SDValue
5163 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5164
5165   // Check if the scalar load can be widened into a vector load. And if
5166   // the address is "base + cst" see if the cst can be "absorbed" into
5167   // the shuffle mask.
5168   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5169     SDValue Ptr = LD->getBasePtr();
5170     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5171       return SDValue();
5172     EVT PVT = LD->getValueType(0);
5173     if (PVT != MVT::i32 && PVT != MVT::f32)
5174       return SDValue();
5175
5176     int FI = -1;
5177     int64_t Offset = 0;
5178     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5179       FI = FINode->getIndex();
5180       Offset = 0;
5181     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5182                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5183       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5184       Offset = Ptr.getConstantOperandVal(1);
5185       Ptr = Ptr.getOperand(0);
5186     } else {
5187       return SDValue();
5188     }
5189
5190     // FIXME: 256-bit vector instructions don't require a strict alignment,
5191     // improve this code to support it better.
5192     unsigned RequiredAlign = VT.getSizeInBits()/8;
5193     SDValue Chain = LD->getChain();
5194     // Make sure the stack object alignment is at least 16 or 32.
5195     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5196     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5197       if (MFI->isFixedObjectIndex(FI)) {
5198         // Can't change the alignment. FIXME: It's possible to compute
5199         // the exact stack offset and reference FI + adjust offset instead.
5200         // If someone *really* cares about this. That's the way to implement it.
5201         return SDValue();
5202       } else {
5203         MFI->setObjectAlignment(FI, RequiredAlign);
5204       }
5205     }
5206
5207     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5208     // Ptr + (Offset & ~15).
5209     if (Offset < 0)
5210       return SDValue();
5211     if ((Offset % RequiredAlign) & 3)
5212       return SDValue();
5213     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5214     if (StartOffset) {
5215       SDLoc DL(Ptr);
5216       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5217                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5218     }
5219
5220     int EltNo = (Offset - StartOffset) >> 2;
5221     unsigned NumElems = VT.getVectorNumElements();
5222
5223     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5224     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5225                              LD->getPointerInfo().getWithOffset(StartOffset),
5226                              false, false, false, 0);
5227
5228     SmallVector<int, 8> Mask(NumElems, EltNo);
5229
5230     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5231   }
5232
5233   return SDValue();
5234 }
5235
5236 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5237 /// elements can be replaced by a single large load which has the same value as
5238 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5239 ///
5240 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5241 ///
5242 /// FIXME: we'd also like to handle the case where the last elements are zero
5243 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5244 /// There's even a handy isZeroNode for that purpose.
5245 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5246                                         SDLoc &DL, SelectionDAG &DAG,
5247                                         bool isAfterLegalize) {
5248   unsigned NumElems = Elts.size();
5249
5250   LoadSDNode *LDBase = nullptr;
5251   unsigned LastLoadedElt = -1U;
5252
5253   // For each element in the initializer, see if we've found a load or an undef.
5254   // If we don't find an initial load element, or later load elements are
5255   // non-consecutive, bail out.
5256   for (unsigned i = 0; i < NumElems; ++i) {
5257     SDValue Elt = Elts[i];
5258     // Look through a bitcast.
5259     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5260       Elt = Elt.getOperand(0);
5261     if (!Elt.getNode() ||
5262         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5263       return SDValue();
5264     if (!LDBase) {
5265       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5266         return SDValue();
5267       LDBase = cast<LoadSDNode>(Elt.getNode());
5268       LastLoadedElt = i;
5269       continue;
5270     }
5271     if (Elt.getOpcode() == ISD::UNDEF)
5272       continue;
5273
5274     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5275     EVT LdVT = Elt.getValueType();
5276     // Each loaded element must be the correct fractional portion of the
5277     // requested vector load.
5278     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5279       return SDValue();
5280     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5281       return SDValue();
5282     LastLoadedElt = i;
5283   }
5284
5285   // If we have found an entire vector of loads and undefs, then return a large
5286   // load of the entire vector width starting at the base pointer.  If we found
5287   // consecutive loads for the low half, generate a vzext_load node.
5288   if (LastLoadedElt == NumElems - 1) {
5289     assert(LDBase && "Did not find base load for merging consecutive loads");
5290     EVT EltVT = LDBase->getValueType(0);
5291     // Ensure that the input vector size for the merged loads matches the
5292     // cumulative size of the input elements.
5293     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5294       return SDValue();
5295
5296     if (isAfterLegalize &&
5297         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5298       return SDValue();
5299
5300     SDValue NewLd = SDValue();
5301
5302     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5303                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5304                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5305                         LDBase->getAlignment());
5306
5307     if (LDBase->hasAnyUseOfValue(1)) {
5308       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5309                                      SDValue(LDBase, 1),
5310                                      SDValue(NewLd.getNode(), 1));
5311       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5312       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5313                              SDValue(NewLd.getNode(), 1));
5314     }
5315
5316     return NewLd;
5317   }
5318
5319   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5320   //of a v4i32 / v4f32. It's probably worth generalizing.
5321   EVT EltVT = VT.getVectorElementType();
5322   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5323       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5324     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5325     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5326     SDValue ResNode =
5327         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5328                                 LDBase->getPointerInfo(),
5329                                 LDBase->getAlignment(),
5330                                 false/*isVolatile*/, true/*ReadMem*/,
5331                                 false/*WriteMem*/);
5332
5333     // Make sure the newly-created LOAD is in the same position as LDBase in
5334     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5335     // update uses of LDBase's output chain to use the TokenFactor.
5336     if (LDBase->hasAnyUseOfValue(1)) {
5337       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5338                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5339       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5340       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5341                              SDValue(ResNode.getNode(), 1));
5342     }
5343
5344     return DAG.getBitcast(VT, ResNode);
5345   }
5346   return SDValue();
5347 }
5348
5349 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5350 /// to generate a splat value for the following cases:
5351 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5352 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5353 /// a scalar load, or a constant.
5354 /// The VBROADCAST node is returned when a pattern is found,
5355 /// or SDValue() otherwise.
5356 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5357                                     SelectionDAG &DAG) {
5358   // VBROADCAST requires AVX.
5359   // TODO: Splats could be generated for non-AVX CPUs using SSE
5360   // instructions, but there's less potential gain for only 128-bit vectors.
5361   if (!Subtarget->hasAVX())
5362     return SDValue();
5363
5364   MVT VT = Op.getSimpleValueType();
5365   SDLoc dl(Op);
5366
5367   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5368          "Unsupported vector type for broadcast.");
5369
5370   SDValue Ld;
5371   bool ConstSplatVal;
5372
5373   switch (Op.getOpcode()) {
5374     default:
5375       // Unknown pattern found.
5376       return SDValue();
5377
5378     case ISD::BUILD_VECTOR: {
5379       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5380       BitVector UndefElements;
5381       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5382
5383       // We need a splat of a single value to use broadcast, and it doesn't
5384       // make any sense if the value is only in one element of the vector.
5385       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5386         return SDValue();
5387
5388       Ld = Splat;
5389       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5390                        Ld.getOpcode() == ISD::ConstantFP);
5391
5392       // Make sure that all of the users of a non-constant load are from the
5393       // BUILD_VECTOR node.
5394       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5395         return SDValue();
5396       break;
5397     }
5398
5399     case ISD::VECTOR_SHUFFLE: {
5400       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5401
5402       // Shuffles must have a splat mask where the first element is
5403       // broadcasted.
5404       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5405         return SDValue();
5406
5407       SDValue Sc = Op.getOperand(0);
5408       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5409           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5410
5411         if (!Subtarget->hasInt256())
5412           return SDValue();
5413
5414         // Use the register form of the broadcast instruction available on AVX2.
5415         if (VT.getSizeInBits() >= 256)
5416           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5417         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5418       }
5419
5420       Ld = Sc.getOperand(0);
5421       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5422                        Ld.getOpcode() == ISD::ConstantFP);
5423
5424       // The scalar_to_vector node and the suspected
5425       // load node must have exactly one user.
5426       // Constants may have multiple users.
5427
5428       // AVX-512 has register version of the broadcast
5429       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5430         Ld.getValueType().getSizeInBits() >= 32;
5431       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5432           !hasRegVer))
5433         return SDValue();
5434       break;
5435     }
5436   }
5437
5438   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5439   bool IsGE256 = (VT.getSizeInBits() >= 256);
5440
5441   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5442   // instruction to save 8 or more bytes of constant pool data.
5443   // TODO: If multiple splats are generated to load the same constant,
5444   // it may be detrimental to overall size. There needs to be a way to detect
5445   // that condition to know if this is truly a size win.
5446   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5447
5448   // Handle broadcasting a single constant scalar from the constant pool
5449   // into a vector.
5450   // On Sandybridge (no AVX2), it is still better to load a constant vector
5451   // from the constant pool and not to broadcast it from a scalar.
5452   // But override that restriction when optimizing for size.
5453   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5454   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5455     EVT CVT = Ld.getValueType();
5456     assert(!CVT.isVector() && "Must not broadcast a vector type");
5457
5458     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5459     // For size optimization, also splat v2f64 and v2i64, and for size opt
5460     // with AVX2, also splat i8 and i16.
5461     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5462     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5463         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5464       const Constant *C = nullptr;
5465       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5466         C = CI->getConstantIntValue();
5467       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5468         C = CF->getConstantFPValue();
5469
5470       assert(C && "Invalid constant type");
5471
5472       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5473       SDValue CP =
5474           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5475       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5476       Ld = DAG.getLoad(
5477           CVT, dl, DAG.getEntryNode(), CP,
5478           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5479           false, false, Alignment);
5480
5481       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5482     }
5483   }
5484
5485   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5486
5487   // Handle AVX2 in-register broadcasts.
5488   if (!IsLoad && Subtarget->hasInt256() &&
5489       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5490     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5491
5492   // The scalar source must be a normal load.
5493   if (!IsLoad)
5494     return SDValue();
5495
5496   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5497       (Subtarget->hasVLX() && ScalarSize == 64))
5498     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5499
5500   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5501   // double since there is no vbroadcastsd xmm
5502   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5503     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5504       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5505   }
5506
5507   // Unsupported broadcast.
5508   return SDValue();
5509 }
5510
5511 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5512 /// underlying vector and index.
5513 ///
5514 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5515 /// index.
5516 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5517                                          SDValue ExtIdx) {
5518   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5519   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5520     return Idx;
5521
5522   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5523   // lowered this:
5524   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5525   // to:
5526   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5527   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5528   //                           undef)
5529   //                       Constant<0>)
5530   // In this case the vector is the extract_subvector expression and the index
5531   // is 2, as specified by the shuffle.
5532   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5533   SDValue ShuffleVec = SVOp->getOperand(0);
5534   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5535   assert(ShuffleVecVT.getVectorElementType() ==
5536          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5537
5538   int ShuffleIdx = SVOp->getMaskElt(Idx);
5539   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5540     ExtractedFromVec = ShuffleVec;
5541     return ShuffleIdx;
5542   }
5543   return Idx;
5544 }
5545
5546 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5547   MVT VT = Op.getSimpleValueType();
5548
5549   // Skip if insert_vec_elt is not supported.
5550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5551   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5552     return SDValue();
5553
5554   SDLoc DL(Op);
5555   unsigned NumElems = Op.getNumOperands();
5556
5557   SDValue VecIn1;
5558   SDValue VecIn2;
5559   SmallVector<unsigned, 4> InsertIndices;
5560   SmallVector<int, 8> Mask(NumElems, -1);
5561
5562   for (unsigned i = 0; i != NumElems; ++i) {
5563     unsigned Opc = Op.getOperand(i).getOpcode();
5564
5565     if (Opc == ISD::UNDEF)
5566       continue;
5567
5568     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5569       // Quit if more than 1 elements need inserting.
5570       if (InsertIndices.size() > 1)
5571         return SDValue();
5572
5573       InsertIndices.push_back(i);
5574       continue;
5575     }
5576
5577     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5578     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5579     // Quit if non-constant index.
5580     if (!isa<ConstantSDNode>(ExtIdx))
5581       return SDValue();
5582     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5583
5584     // Quit if extracted from vector of different type.
5585     if (ExtractedFromVec.getValueType() != VT)
5586       return SDValue();
5587
5588     if (!VecIn1.getNode())
5589       VecIn1 = ExtractedFromVec;
5590     else if (VecIn1 != ExtractedFromVec) {
5591       if (!VecIn2.getNode())
5592         VecIn2 = ExtractedFromVec;
5593       else if (VecIn2 != ExtractedFromVec)
5594         // Quit if more than 2 vectors to shuffle
5595         return SDValue();
5596     }
5597
5598     if (ExtractedFromVec == VecIn1)
5599       Mask[i] = Idx;
5600     else if (ExtractedFromVec == VecIn2)
5601       Mask[i] = Idx + NumElems;
5602   }
5603
5604   if (!VecIn1.getNode())
5605     return SDValue();
5606
5607   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5608   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5609   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5610     unsigned Idx = InsertIndices[i];
5611     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5612                      DAG.getIntPtrConstant(Idx, DL));
5613   }
5614
5615   return NV;
5616 }
5617
5618 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5619   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5620          Op.getScalarValueSizeInBits() == 1 &&
5621          "Can not convert non-constant vector");
5622   uint64_t Immediate = 0;
5623   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5624     SDValue In = Op.getOperand(idx);
5625     if (In.getOpcode() != ISD::UNDEF)
5626       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5627   }
5628   SDLoc dl(Op);
5629   MVT VT =
5630    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5631   return DAG.getConstant(Immediate, dl, VT);
5632 }
5633 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5634 SDValue
5635 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5636
5637   MVT VT = Op.getSimpleValueType();
5638   assert((VT.getVectorElementType() == MVT::i1) &&
5639          "Unexpected type in LowerBUILD_VECTORvXi1!");
5640
5641   SDLoc dl(Op);
5642   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5643     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5644     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5645     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5646   }
5647
5648   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5649     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5650     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5651     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5652   }
5653
5654   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5655     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5656     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5657       return DAG.getBitcast(VT, Imm);
5658     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5659     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5660                         DAG.getIntPtrConstant(0, dl));
5661   }
5662
5663   // Vector has one or more non-const elements
5664   uint64_t Immediate = 0;
5665   SmallVector<unsigned, 16> NonConstIdx;
5666   bool IsSplat = true;
5667   bool HasConstElts = false;
5668   int SplatIdx = -1;
5669   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5670     SDValue In = Op.getOperand(idx);
5671     if (In.getOpcode() == ISD::UNDEF)
5672       continue;
5673     if (!isa<ConstantSDNode>(In))
5674       NonConstIdx.push_back(idx);
5675     else {
5676       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5677       HasConstElts = true;
5678     }
5679     if (SplatIdx == -1)
5680       SplatIdx = idx;
5681     else if (In != Op.getOperand(SplatIdx))
5682       IsSplat = false;
5683   }
5684
5685   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5686   if (IsSplat)
5687     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5688                        DAG.getConstant(1, dl, VT),
5689                        DAG.getConstant(0, dl, VT));
5690
5691   // insert elements one by one
5692   SDValue DstVec;
5693   SDValue Imm;
5694   if (Immediate) {
5695     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5696     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5697   }
5698   else if (HasConstElts)
5699     Imm = DAG.getConstant(0, dl, VT);
5700   else
5701     Imm = DAG.getUNDEF(VT);
5702   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5703     DstVec = DAG.getBitcast(VT, Imm);
5704   else {
5705     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5706     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5707                          DAG.getIntPtrConstant(0, dl));
5708   }
5709
5710   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5711     unsigned InsertIdx = NonConstIdx[i];
5712     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5713                          Op.getOperand(InsertIdx),
5714                          DAG.getIntPtrConstant(InsertIdx, dl));
5715   }
5716   return DstVec;
5717 }
5718
5719 /// \brief Return true if \p N implements a horizontal binop and return the
5720 /// operands for the horizontal binop into V0 and V1.
5721 ///
5722 /// This is a helper function of LowerToHorizontalOp().
5723 /// This function checks that the build_vector \p N in input implements a
5724 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5725 /// operation to match.
5726 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5727 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5728 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5729 /// arithmetic sub.
5730 ///
5731 /// This function only analyzes elements of \p N whose indices are
5732 /// in range [BaseIdx, LastIdx).
5733 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5734                               SelectionDAG &DAG,
5735                               unsigned BaseIdx, unsigned LastIdx,
5736                               SDValue &V0, SDValue &V1) {
5737   EVT VT = N->getValueType(0);
5738
5739   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5740   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5741          "Invalid Vector in input!");
5742
5743   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5744   bool CanFold = true;
5745   unsigned ExpectedVExtractIdx = BaseIdx;
5746   unsigned NumElts = LastIdx - BaseIdx;
5747   V0 = DAG.getUNDEF(VT);
5748   V1 = DAG.getUNDEF(VT);
5749
5750   // Check if N implements a horizontal binop.
5751   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5752     SDValue Op = N->getOperand(i + BaseIdx);
5753
5754     // Skip UNDEFs.
5755     if (Op->getOpcode() == ISD::UNDEF) {
5756       // Update the expected vector extract index.
5757       if (i * 2 == NumElts)
5758         ExpectedVExtractIdx = BaseIdx;
5759       ExpectedVExtractIdx += 2;
5760       continue;
5761     }
5762
5763     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5764
5765     if (!CanFold)
5766       break;
5767
5768     SDValue Op0 = Op.getOperand(0);
5769     SDValue Op1 = Op.getOperand(1);
5770
5771     // Try to match the following pattern:
5772     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5773     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5774         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5775         Op0.getOperand(0) == Op1.getOperand(0) &&
5776         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5777         isa<ConstantSDNode>(Op1.getOperand(1)));
5778     if (!CanFold)
5779       break;
5780
5781     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5782     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5783
5784     if (i * 2 < NumElts) {
5785       if (V0.getOpcode() == ISD::UNDEF) {
5786         V0 = Op0.getOperand(0);
5787         if (V0.getValueType() != VT)
5788           return false;
5789       }
5790     } else {
5791       if (V1.getOpcode() == ISD::UNDEF) {
5792         V1 = Op0.getOperand(0);
5793         if (V1.getValueType() != VT)
5794           return false;
5795       }
5796       if (i * 2 == NumElts)
5797         ExpectedVExtractIdx = BaseIdx;
5798     }
5799
5800     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5801     if (I0 == ExpectedVExtractIdx)
5802       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5803     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5804       // Try to match the following dag sequence:
5805       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5806       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5807     } else
5808       CanFold = false;
5809
5810     ExpectedVExtractIdx += 2;
5811   }
5812
5813   return CanFold;
5814 }
5815
5816 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5817 /// a concat_vector.
5818 ///
5819 /// This is a helper function of LowerToHorizontalOp().
5820 /// This function expects two 256-bit vectors called V0 and V1.
5821 /// At first, each vector is split into two separate 128-bit vectors.
5822 /// Then, the resulting 128-bit vectors are used to implement two
5823 /// horizontal binary operations.
5824 ///
5825 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5826 ///
5827 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5828 /// the two new horizontal binop.
5829 /// When Mode is set, the first horizontal binop dag node would take as input
5830 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5831 /// horizontal binop dag node would take as input the lower 128-bit of V1
5832 /// and the upper 128-bit of V1.
5833 ///   Example:
5834 ///     HADD V0_LO, V0_HI
5835 ///     HADD V1_LO, V1_HI
5836 ///
5837 /// Otherwise, the first horizontal binop dag node takes as input the lower
5838 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5839 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5840 ///   Example:
5841 ///     HADD V0_LO, V1_LO
5842 ///     HADD V0_HI, V1_HI
5843 ///
5844 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5845 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5846 /// the upper 128-bits of the result.
5847 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5848                                      SDLoc DL, SelectionDAG &DAG,
5849                                      unsigned X86Opcode, bool Mode,
5850                                      bool isUndefLO, bool isUndefHI) {
5851   EVT VT = V0.getValueType();
5852   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5853          "Invalid nodes in input!");
5854
5855   unsigned NumElts = VT.getVectorNumElements();
5856   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5857   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5858   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5859   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5860   EVT NewVT = V0_LO.getValueType();
5861
5862   SDValue LO = DAG.getUNDEF(NewVT);
5863   SDValue HI = DAG.getUNDEF(NewVT);
5864
5865   if (Mode) {
5866     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5867     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5868       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5869     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5870       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5871   } else {
5872     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5873     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5874                        V1_LO->getOpcode() != ISD::UNDEF))
5875       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5876
5877     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5878                        V1_HI->getOpcode() != ISD::UNDEF))
5879       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5880   }
5881
5882   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5883 }
5884
5885 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5886 /// node.
5887 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5888                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5889   MVT VT = BV->getSimpleValueType(0);
5890   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5891       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5892     return SDValue();
5893
5894   SDLoc DL(BV);
5895   unsigned NumElts = VT.getVectorNumElements();
5896   SDValue InVec0 = DAG.getUNDEF(VT);
5897   SDValue InVec1 = DAG.getUNDEF(VT);
5898
5899   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5900           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5901
5902   // Odd-numbered elements in the input build vector are obtained from
5903   // adding two integer/float elements.
5904   // Even-numbered elements in the input build vector are obtained from
5905   // subtracting two integer/float elements.
5906   unsigned ExpectedOpcode = ISD::FSUB;
5907   unsigned NextExpectedOpcode = ISD::FADD;
5908   bool AddFound = false;
5909   bool SubFound = false;
5910
5911   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5912     SDValue Op = BV->getOperand(i);
5913
5914     // Skip 'undef' values.
5915     unsigned Opcode = Op.getOpcode();
5916     if (Opcode == ISD::UNDEF) {
5917       std::swap(ExpectedOpcode, NextExpectedOpcode);
5918       continue;
5919     }
5920
5921     // Early exit if we found an unexpected opcode.
5922     if (Opcode != ExpectedOpcode)
5923       return SDValue();
5924
5925     SDValue Op0 = Op.getOperand(0);
5926     SDValue Op1 = Op.getOperand(1);
5927
5928     // Try to match the following pattern:
5929     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5930     // Early exit if we cannot match that sequence.
5931     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5932         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5933         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5934         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5935         Op0.getOperand(1) != Op1.getOperand(1))
5936       return SDValue();
5937
5938     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5939     if (I0 != i)
5940       return SDValue();
5941
5942     // We found a valid add/sub node. Update the information accordingly.
5943     if (i & 1)
5944       AddFound = true;
5945     else
5946       SubFound = true;
5947
5948     // Update InVec0 and InVec1.
5949     if (InVec0.getOpcode() == ISD::UNDEF) {
5950       InVec0 = Op0.getOperand(0);
5951       if (InVec0.getSimpleValueType() != VT)
5952         return SDValue();
5953     }
5954     if (InVec1.getOpcode() == ISD::UNDEF) {
5955       InVec1 = Op1.getOperand(0);
5956       if (InVec1.getSimpleValueType() != VT)
5957         return SDValue();
5958     }
5959
5960     // Make sure that operands in input to each add/sub node always
5961     // come from a same pair of vectors.
5962     if (InVec0 != Op0.getOperand(0)) {
5963       if (ExpectedOpcode == ISD::FSUB)
5964         return SDValue();
5965
5966       // FADD is commutable. Try to commute the operands
5967       // and then test again.
5968       std::swap(Op0, Op1);
5969       if (InVec0 != Op0.getOperand(0))
5970         return SDValue();
5971     }
5972
5973     if (InVec1 != Op1.getOperand(0))
5974       return SDValue();
5975
5976     // Update the pair of expected opcodes.
5977     std::swap(ExpectedOpcode, NextExpectedOpcode);
5978   }
5979
5980   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5981   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5982       InVec1.getOpcode() != ISD::UNDEF)
5983     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5984
5985   return SDValue();
5986 }
5987
5988 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5989 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5990                                    const X86Subtarget *Subtarget,
5991                                    SelectionDAG &DAG) {
5992   MVT VT = BV->getSimpleValueType(0);
5993   unsigned NumElts = VT.getVectorNumElements();
5994   unsigned NumUndefsLO = 0;
5995   unsigned NumUndefsHI = 0;
5996   unsigned Half = NumElts/2;
5997
5998   // Count the number of UNDEF operands in the build_vector in input.
5999   for (unsigned i = 0, e = Half; i != e; ++i)
6000     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6001       NumUndefsLO++;
6002
6003   for (unsigned i = Half, e = NumElts; i != e; ++i)
6004     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6005       NumUndefsHI++;
6006
6007   // Early exit if this is either a build_vector of all UNDEFs or all the
6008   // operands but one are UNDEF.
6009   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6010     return SDValue();
6011
6012   SDLoc DL(BV);
6013   SDValue InVec0, InVec1;
6014   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6015     // Try to match an SSE3 float HADD/HSUB.
6016     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6017       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6018
6019     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6020       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6021   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6022     // Try to match an SSSE3 integer HADD/HSUB.
6023     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6024       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6025
6026     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6027       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6028   }
6029
6030   if (!Subtarget->hasAVX())
6031     return SDValue();
6032
6033   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6034     // Try to match an AVX horizontal add/sub of packed single/double
6035     // precision floating point values from 256-bit vectors.
6036     SDValue InVec2, InVec3;
6037     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6038         isHorizontalBinOp(BV, ISD::FADD, 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::FHADD, DL, VT, InVec0, InVec1);
6044
6045     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6046         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6047         ((InVec0.getOpcode() == ISD::UNDEF ||
6048           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6049         ((InVec1.getOpcode() == ISD::UNDEF ||
6050           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6051       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6052   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6053     // Try to match an AVX2 horizontal add/sub of signed integers.
6054     SDValue InVec2, InVec3;
6055     unsigned X86Opcode;
6056     bool CanFold = true;
6057
6058     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6059         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6060         ((InVec0.getOpcode() == ISD::UNDEF ||
6061           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6062         ((InVec1.getOpcode() == ISD::UNDEF ||
6063           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6064       X86Opcode = X86ISD::HADD;
6065     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6066         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6067         ((InVec0.getOpcode() == ISD::UNDEF ||
6068           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6069         ((InVec1.getOpcode() == ISD::UNDEF ||
6070           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6071       X86Opcode = X86ISD::HSUB;
6072     else
6073       CanFold = false;
6074
6075     if (CanFold) {
6076       // Fold this build_vector into a single horizontal add/sub.
6077       // Do this only if the target has AVX2.
6078       if (Subtarget->hasAVX2())
6079         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6080
6081       // Do not try to expand this build_vector into a pair of horizontal
6082       // add/sub if we can emit a pair of scalar add/sub.
6083       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6084         return SDValue();
6085
6086       // Convert this build_vector into a pair of horizontal binop followed by
6087       // a concat vector.
6088       bool isUndefLO = NumUndefsLO == Half;
6089       bool isUndefHI = NumUndefsHI == Half;
6090       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6091                                    isUndefLO, isUndefHI);
6092     }
6093   }
6094
6095   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6096        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6097     unsigned X86Opcode;
6098     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6099       X86Opcode = X86ISD::HADD;
6100     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6101       X86Opcode = X86ISD::HSUB;
6102     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6103       X86Opcode = X86ISD::FHADD;
6104     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6105       X86Opcode = X86ISD::FHSUB;
6106     else
6107       return SDValue();
6108
6109     // Don't try to expand this build_vector into a pair of horizontal add/sub
6110     // if we can simply emit a pair of scalar add/sub.
6111     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6112       return SDValue();
6113
6114     // Convert this build_vector into two horizontal add/sub followed by
6115     // a concat vector.
6116     bool isUndefLO = NumUndefsLO == Half;
6117     bool isUndefHI = NumUndefsHI == Half;
6118     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6119                                  isUndefLO, isUndefHI);
6120   }
6121
6122   return SDValue();
6123 }
6124
6125 SDValue
6126 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6127   SDLoc dl(Op);
6128
6129   MVT VT = Op.getSimpleValueType();
6130   MVT ExtVT = VT.getVectorElementType();
6131   unsigned NumElems = Op.getNumOperands();
6132
6133   // Generate vectors for predicate vectors.
6134   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6135     return LowerBUILD_VECTORvXi1(Op, DAG);
6136
6137   // Vectors containing all zeros can be matched by pxor and xorps later
6138   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6139     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6140     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6141     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6142       return Op;
6143
6144     return getZeroVector(VT, Subtarget, DAG, dl);
6145   }
6146
6147   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6148   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6149   // vpcmpeqd on 256-bit vectors.
6150   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6151     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6152       return Op;
6153
6154     if (!VT.is512BitVector())
6155       return getOnesVector(VT, Subtarget, DAG, dl);
6156   }
6157
6158   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6159   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6160     return AddSub;
6161   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6162     return HorizontalOp;
6163   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6164     return Broadcast;
6165
6166   unsigned EVTBits = ExtVT.getSizeInBits();
6167
6168   unsigned NumZero  = 0;
6169   unsigned NumNonZero = 0;
6170   unsigned NonZeros = 0;
6171   bool IsAllConstants = true;
6172   SmallSet<SDValue, 8> Values;
6173   for (unsigned i = 0; i < NumElems; ++i) {
6174     SDValue Elt = Op.getOperand(i);
6175     if (Elt.getOpcode() == ISD::UNDEF)
6176       continue;
6177     Values.insert(Elt);
6178     if (Elt.getOpcode() != ISD::Constant &&
6179         Elt.getOpcode() != ISD::ConstantFP)
6180       IsAllConstants = false;
6181     if (X86::isZeroNode(Elt))
6182       NumZero++;
6183     else {
6184       NonZeros |= (1 << i);
6185       NumNonZero++;
6186     }
6187   }
6188
6189   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6190   if (NumNonZero == 0)
6191     return DAG.getUNDEF(VT);
6192
6193   // Special case for single non-zero, non-undef, element.
6194   if (NumNonZero == 1) {
6195     unsigned Idx = countTrailingZeros(NonZeros);
6196     SDValue Item = Op.getOperand(Idx);
6197
6198     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6199     // the value are obviously zero, truncate the value to i32 and do the
6200     // insertion that way.  Only do this if the value is non-constant or if the
6201     // value is a constant being inserted into element 0.  It is cheaper to do
6202     // a constant pool load than it is to do a movd + shuffle.
6203     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6204         (!IsAllConstants || Idx == 0)) {
6205       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6206         // Handle SSE only.
6207         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6208         MVT VecVT = MVT::v4i32;
6209
6210         // Truncate the value (which may itself be a constant) to i32, and
6211         // convert it to a vector with movd (S2V+shuffle to zero extend).
6212         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6213         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6214         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6215                                       Item, Idx * 2, true, Subtarget, DAG));
6216       }
6217     }
6218
6219     // If we have a constant or non-constant insertion into the low element of
6220     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6221     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6222     // depending on what the source datatype is.
6223     if (Idx == 0) {
6224       if (NumZero == 0)
6225         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6226
6227       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6228           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6229         if (VT.is512BitVector()) {
6230           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6231           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6232                              Item, DAG.getIntPtrConstant(0, dl));
6233         }
6234         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6235                "Expected an SSE value type!");
6236         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6237         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6238         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6239       }
6240
6241       // We can't directly insert an i8 or i16 into a vector, so zero extend
6242       // it to i32 first.
6243       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6244         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6245         if (VT.is256BitVector()) {
6246           if (Subtarget->hasAVX()) {
6247             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6248             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6249           } else {
6250             // Without AVX, we need to extend to a 128-bit vector and then
6251             // insert into the 256-bit vector.
6252             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6253             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6254             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6255           }
6256         } else {
6257           assert(VT.is128BitVector() && "Expected an SSE value type!");
6258           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6259           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6260         }
6261         return DAG.getBitcast(VT, Item);
6262       }
6263     }
6264
6265     // Is it a vector logical left shift?
6266     if (NumElems == 2 && Idx == 1 &&
6267         X86::isZeroNode(Op.getOperand(0)) &&
6268         !X86::isZeroNode(Op.getOperand(1))) {
6269       unsigned NumBits = VT.getSizeInBits();
6270       return getVShift(true, VT,
6271                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6272                                    VT, Op.getOperand(1)),
6273                        NumBits/2, DAG, *this, dl);
6274     }
6275
6276     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6277       return SDValue();
6278
6279     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6280     // is a non-constant being inserted into an element other than the low one,
6281     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6282     // movd/movss) to move this into the low element, then shuffle it into
6283     // place.
6284     if (EVTBits == 32) {
6285       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6286       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6287     }
6288   }
6289
6290   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6291   if (Values.size() == 1) {
6292     if (EVTBits == 32) {
6293       // Instead of a shuffle like this:
6294       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6295       // Check if it's possible to issue this instead.
6296       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6297       unsigned Idx = countTrailingZeros(NonZeros);
6298       SDValue Item = Op.getOperand(Idx);
6299       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6300         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6301     }
6302     return SDValue();
6303   }
6304
6305   // A vector full of immediates; various special cases are already
6306   // handled, so this is best done with a single constant-pool load.
6307   if (IsAllConstants)
6308     return SDValue();
6309
6310   // For AVX-length vectors, see if we can use a vector load to get all of the
6311   // elements, otherwise build the individual 128-bit pieces and use
6312   // shuffles to put them in place.
6313   if (VT.is256BitVector() || VT.is512BitVector()) {
6314     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6315
6316     // Check for a build vector of consecutive loads.
6317     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6318       return LD;
6319
6320     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6321
6322     // Build both the lower and upper subvector.
6323     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6324                                 makeArrayRef(&V[0], NumElems/2));
6325     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6326                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6327
6328     // Recreate the wider vector with the lower and upper part.
6329     if (VT.is256BitVector())
6330       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6331     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6332   }
6333
6334   // Let legalizer expand 2-wide build_vectors.
6335   if (EVTBits == 64) {
6336     if (NumNonZero == 1) {
6337       // One half is zero or undef.
6338       unsigned Idx = countTrailingZeros(NonZeros);
6339       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6340                                  Op.getOperand(Idx));
6341       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6342     }
6343     return SDValue();
6344   }
6345
6346   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6347   if (EVTBits == 8 && NumElems == 16)
6348     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6349                                         Subtarget, *this))
6350       return V;
6351
6352   if (EVTBits == 16 && NumElems == 8)
6353     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6354                                       Subtarget, *this))
6355       return V;
6356
6357   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6358   if (EVTBits == 32 && NumElems == 4)
6359     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6360       return V;
6361
6362   // If element VT is == 32 bits, turn it into a number of shuffles.
6363   SmallVector<SDValue, 8> V(NumElems);
6364   if (NumElems == 4 && NumZero > 0) {
6365     for (unsigned i = 0; i < 4; ++i) {
6366       bool isZero = !(NonZeros & (1 << i));
6367       if (isZero)
6368         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6369       else
6370         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6371     }
6372
6373     for (unsigned i = 0; i < 2; ++i) {
6374       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6375         default: break;
6376         case 0:
6377           V[i] = V[i*2];  // Must be a zero vector.
6378           break;
6379         case 1:
6380           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6381           break;
6382         case 2:
6383           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6384           break;
6385         case 3:
6386           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6387           break;
6388       }
6389     }
6390
6391     bool Reverse1 = (NonZeros & 0x3) == 2;
6392     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6393     int MaskVec[] = {
6394       Reverse1 ? 1 : 0,
6395       Reverse1 ? 0 : 1,
6396       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6397       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6398     };
6399     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6400   }
6401
6402   if (Values.size() > 1 && VT.is128BitVector()) {
6403     // Check for a build vector of consecutive loads.
6404     for (unsigned i = 0; i < NumElems; ++i)
6405       V[i] = Op.getOperand(i);
6406
6407     // Check for elements which are consecutive loads.
6408     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6409       return LD;
6410
6411     // Check for a build vector from mostly shuffle plus few inserting.
6412     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6413       return Sh;
6414
6415     // For SSE 4.1, use insertps to put the high elements into the low element.
6416     if (Subtarget->hasSSE41()) {
6417       SDValue Result;
6418       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6419         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6420       else
6421         Result = DAG.getUNDEF(VT);
6422
6423       for (unsigned i = 1; i < NumElems; ++i) {
6424         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6425         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6426                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6427       }
6428       return Result;
6429     }
6430
6431     // Otherwise, expand into a number of unpckl*, start by extending each of
6432     // our (non-undef) elements to the full vector width with the element in the
6433     // bottom slot of the vector (which generates no code for SSE).
6434     for (unsigned i = 0; i < NumElems; ++i) {
6435       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6436         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6437       else
6438         V[i] = DAG.getUNDEF(VT);
6439     }
6440
6441     // Next, we iteratively mix elements, e.g. for v4f32:
6442     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6443     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6444     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6445     unsigned EltStride = NumElems >> 1;
6446     while (EltStride != 0) {
6447       for (unsigned i = 0; i < EltStride; ++i) {
6448         // If V[i+EltStride] is undef and this is the first round of mixing,
6449         // then it is safe to just drop this shuffle: V[i] is already in the
6450         // right place, the one element (since it's the first round) being
6451         // inserted as undef can be dropped.  This isn't safe for successive
6452         // rounds because they will permute elements within both vectors.
6453         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6454             EltStride == NumElems/2)
6455           continue;
6456
6457         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6458       }
6459       EltStride >>= 1;
6460     }
6461     return V[0];
6462   }
6463   return SDValue();
6464 }
6465
6466 // 256-bit AVX can use the vinsertf128 instruction
6467 // to create 256-bit vectors from two other 128-bit ones.
6468 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6469   SDLoc dl(Op);
6470   MVT ResVT = Op.getSimpleValueType();
6471
6472   assert((ResVT.is256BitVector() ||
6473           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6474
6475   SDValue V1 = Op.getOperand(0);
6476   SDValue V2 = Op.getOperand(1);
6477   unsigned NumElems = ResVT.getVectorNumElements();
6478   if (ResVT.is256BitVector())
6479     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6480
6481   if (Op.getNumOperands() == 4) {
6482     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6483                                   ResVT.getVectorNumElements()/2);
6484     SDValue V3 = Op.getOperand(2);
6485     SDValue V4 = Op.getOperand(3);
6486     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6487       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6488   }
6489   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6490 }
6491
6492 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6493                                        const X86Subtarget *Subtarget,
6494                                        SelectionDAG & DAG) {
6495   SDLoc dl(Op);
6496   MVT ResVT = Op.getSimpleValueType();
6497   unsigned NumOfOperands = Op.getNumOperands();
6498
6499   assert(isPowerOf2_32(NumOfOperands) &&
6500          "Unexpected number of operands in CONCAT_VECTORS");
6501
6502   if (NumOfOperands > 2) {
6503     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6504                                   ResVT.getVectorNumElements()/2);
6505     SmallVector<SDValue, 2> Ops;
6506     for (unsigned i = 0; i < NumOfOperands/2; i++)
6507       Ops.push_back(Op.getOperand(i));
6508     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6509     Ops.clear();
6510     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6511       Ops.push_back(Op.getOperand(i));
6512     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6513     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6514   }
6515
6516   SDValue V1 = Op.getOperand(0);
6517   SDValue V2 = Op.getOperand(1);
6518   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6519   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6520
6521   if (IsZeroV1 && IsZeroV2)
6522     return getZeroVector(ResVT, Subtarget, DAG, dl);
6523
6524   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6525   SDValue Undef = DAG.getUNDEF(ResVT);
6526   unsigned NumElems = ResVT.getVectorNumElements();
6527   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6528
6529   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6530   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6531   if (IsZeroV1)
6532     return V2;
6533
6534   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6535   // Zero the upper bits of V1
6536   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6537   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6538   if (IsZeroV2)
6539     return V1;
6540   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6541 }
6542
6543 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6544                                    const X86Subtarget *Subtarget,
6545                                    SelectionDAG &DAG) {
6546   MVT VT = Op.getSimpleValueType();
6547   if (VT.getVectorElementType() == MVT::i1)
6548     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6549
6550   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6551          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6552           Op.getNumOperands() == 4)));
6553
6554   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6555   // from two other 128-bit ones.
6556
6557   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6558   return LowerAVXCONCAT_VECTORS(Op, DAG);
6559 }
6560
6561 //===----------------------------------------------------------------------===//
6562 // Vector shuffle lowering
6563 //
6564 // This is an experimental code path for lowering vector shuffles on x86. It is
6565 // designed to handle arbitrary vector shuffles and blends, gracefully
6566 // degrading performance as necessary. It works hard to recognize idiomatic
6567 // shuffles and lower them to optimal instruction patterns without leaving
6568 // a framework that allows reasonably efficient handling of all vector shuffle
6569 // patterns.
6570 //===----------------------------------------------------------------------===//
6571
6572 /// \brief Tiny helper function to identify a no-op mask.
6573 ///
6574 /// This is a somewhat boring predicate function. It checks whether the mask
6575 /// array input, which is assumed to be a single-input shuffle mask of the kind
6576 /// used by the X86 shuffle instructions (not a fully general
6577 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6578 /// in-place shuffle are 'no-op's.
6579 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6580   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6581     if (Mask[i] != -1 && Mask[i] != i)
6582       return false;
6583   return true;
6584 }
6585
6586 /// \brief Helper function to classify a mask as a single-input mask.
6587 ///
6588 /// This isn't a generic single-input test because in the vector shuffle
6589 /// lowering we canonicalize single inputs to be the first input operand. This
6590 /// means we can more quickly test for a single input by only checking whether
6591 /// an input from the second operand exists. We also assume that the size of
6592 /// mask corresponds to the size of the input vectors which isn't true in the
6593 /// fully general case.
6594 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6595   for (int M : Mask)
6596     if (M >= (int)Mask.size())
6597       return false;
6598   return true;
6599 }
6600
6601 /// \brief Test whether there are elements crossing 128-bit lanes in this
6602 /// shuffle mask.
6603 ///
6604 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6605 /// and we routinely test for these.
6606 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6607   int LaneSize = 128 / VT.getScalarSizeInBits();
6608   int Size = Mask.size();
6609   for (int i = 0; i < Size; ++i)
6610     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6611       return true;
6612   return false;
6613 }
6614
6615 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6616 ///
6617 /// This checks a shuffle mask to see if it is performing the same
6618 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6619 /// that it is also not lane-crossing. It may however involve a blend from the
6620 /// same lane of a second vector.
6621 ///
6622 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6623 /// non-trivial to compute in the face of undef lanes. The representation is
6624 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6625 /// entries from both V1 and V2 inputs to the wider mask.
6626 static bool
6627 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6628                                 SmallVectorImpl<int> &RepeatedMask) {
6629   int LaneSize = 128 / VT.getScalarSizeInBits();
6630   RepeatedMask.resize(LaneSize, -1);
6631   int Size = Mask.size();
6632   for (int i = 0; i < Size; ++i) {
6633     if (Mask[i] < 0)
6634       continue;
6635     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6636       // This entry crosses lanes, so there is no way to model this shuffle.
6637       return false;
6638
6639     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6640     if (RepeatedMask[i % LaneSize] == -1)
6641       // This is the first non-undef entry in this slot of a 128-bit lane.
6642       RepeatedMask[i % LaneSize] =
6643           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6644     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6645       // Found a mismatch with the repeated mask.
6646       return false;
6647   }
6648   return true;
6649 }
6650
6651 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6652 /// arguments.
6653 ///
6654 /// This is a fast way to test a shuffle mask against a fixed pattern:
6655 ///
6656 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6657 ///
6658 /// It returns true if the mask is exactly as wide as the argument list, and
6659 /// each element of the mask is either -1 (signifying undef) or the value given
6660 /// in the argument.
6661 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6662                                 ArrayRef<int> ExpectedMask) {
6663   if (Mask.size() != ExpectedMask.size())
6664     return false;
6665
6666   int Size = Mask.size();
6667
6668   // If the values are build vectors, we can look through them to find
6669   // equivalent inputs that make the shuffles equivalent.
6670   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6671   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6672
6673   for (int i = 0; i < Size; ++i)
6674     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6675       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6676       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6677       if (!MaskBV || !ExpectedBV ||
6678           MaskBV->getOperand(Mask[i] % Size) !=
6679               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6680         return false;
6681     }
6682
6683   return true;
6684 }
6685
6686 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6687 ///
6688 /// This helper function produces an 8-bit shuffle immediate corresponding to
6689 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6690 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6691 /// example.
6692 ///
6693 /// NB: We rely heavily on "undef" masks preserving the input lane.
6694 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6695                                           SelectionDAG &DAG) {
6696   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6697   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6698   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6699   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6700   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6701
6702   unsigned Imm = 0;
6703   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6704   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6705   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6706   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6707   return DAG.getConstant(Imm, DL, MVT::i8);
6708 }
6709
6710 /// \brief Compute whether each element of a shuffle is zeroable.
6711 ///
6712 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6713 /// Either it is an undef element in the shuffle mask, the element of the input
6714 /// referenced is undef, or the element of the input referenced is known to be
6715 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6716 /// as many lanes with this technique as possible to simplify the remaining
6717 /// shuffle.
6718 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6719                                                      SDValue V1, SDValue V2) {
6720   SmallBitVector Zeroable(Mask.size(), false);
6721
6722   while (V1.getOpcode() == ISD::BITCAST)
6723     V1 = V1->getOperand(0);
6724   while (V2.getOpcode() == ISD::BITCAST)
6725     V2 = V2->getOperand(0);
6726
6727   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6728   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6729
6730   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6731     int M = Mask[i];
6732     // Handle the easy cases.
6733     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6734       Zeroable[i] = true;
6735       continue;
6736     }
6737
6738     // If this is an index into a build_vector node (which has the same number
6739     // of elements), dig out the input value and use it.
6740     SDValue V = M < Size ? V1 : V2;
6741     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6742       continue;
6743
6744     SDValue Input = V.getOperand(M % Size);
6745     // The UNDEF opcode check really should be dead code here, but not quite
6746     // worth asserting on (it isn't invalid, just unexpected).
6747     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6748       Zeroable[i] = true;
6749   }
6750
6751   return Zeroable;
6752 }
6753
6754 // X86 has dedicated unpack instructions that can handle specific blend
6755 // operations: UNPCKH and UNPCKL.
6756 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6757                                            SDValue V1, SDValue V2,
6758                                            SelectionDAG &DAG) {
6759   int NumElts = VT.getVectorNumElements();
6760   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6761   SmallVector<int, 8> Unpckl;
6762   SmallVector<int, 8> Unpckh;
6763
6764   for (int i = 0; i < NumElts; ++i) {
6765     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6766     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6767     int HiPos = LoPos + NumEltsInLane / 2;
6768     Unpckl.push_back(LoPos);
6769     Unpckh.push_back(HiPos);
6770   }
6771
6772   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6773     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6774   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6775     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6776
6777   // Commute and try again.
6778   ShuffleVectorSDNode::commuteMask(Unpckl);
6779   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6780     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6781
6782   ShuffleVectorSDNode::commuteMask(Unpckh);
6783   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6784     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6785
6786   return SDValue();
6787 }
6788
6789 /// \brief Try to emit a bitmask instruction for a shuffle.
6790 ///
6791 /// This handles cases where we can model a blend exactly as a bitmask due to
6792 /// one of the inputs being zeroable.
6793 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6794                                            SDValue V2, ArrayRef<int> Mask,
6795                                            SelectionDAG &DAG) {
6796   MVT EltVT = VT.getVectorElementType();
6797   int NumEltBits = EltVT.getSizeInBits();
6798   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6799   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6800   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6801                                     IntEltVT);
6802   if (EltVT.isFloatingPoint()) {
6803     Zero = DAG.getBitcast(EltVT, Zero);
6804     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6805   }
6806   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6807   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6808   SDValue V;
6809   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6810     if (Zeroable[i])
6811       continue;
6812     if (Mask[i] % Size != i)
6813       return SDValue(); // Not a blend.
6814     if (!V)
6815       V = Mask[i] < Size ? V1 : V2;
6816     else if (V != (Mask[i] < Size ? V1 : V2))
6817       return SDValue(); // Can only let one input through the mask.
6818
6819     VMaskOps[i] = AllOnes;
6820   }
6821   if (!V)
6822     return SDValue(); // No non-zeroable elements!
6823
6824   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6825   V = DAG.getNode(VT.isFloatingPoint()
6826                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6827                   DL, VT, V, VMask);
6828   return V;
6829 }
6830
6831 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6832 ///
6833 /// This is used as a fallback approach when first class blend instructions are
6834 /// unavailable. Currently it is only suitable for integer vectors, but could
6835 /// be generalized for floating point vectors if desirable.
6836 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6837                                             SDValue V2, ArrayRef<int> Mask,
6838                                             SelectionDAG &DAG) {
6839   assert(VT.isInteger() && "Only supports integer vector types!");
6840   MVT EltVT = VT.getVectorElementType();
6841   int NumEltBits = EltVT.getSizeInBits();
6842   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6843   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6844                                     EltVT);
6845   SmallVector<SDValue, 16> MaskOps;
6846   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6847     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6848       return SDValue(); // Shuffled input!
6849     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6850   }
6851
6852   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6853   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6854   // We have to cast V2 around.
6855   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6856   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6857                                       DAG.getBitcast(MaskVT, V1Mask),
6858                                       DAG.getBitcast(MaskVT, V2)));
6859   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6860 }
6861
6862 /// \brief Try to emit a blend instruction for a shuffle.
6863 ///
6864 /// This doesn't do any checks for the availability of instructions for blending
6865 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6866 /// be matched in the backend with the type given. What it does check for is
6867 /// that the shuffle mask is a blend, or convertible into a blend with zero.
6868 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6869                                          SDValue V2, ArrayRef<int> Original,
6870                                          const X86Subtarget *Subtarget,
6871                                          SelectionDAG &DAG) {
6872   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6873   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6874   SmallVector<int, 8> Mask(Original.begin(), Original.end());
6875   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6876   bool ForceV1Zero = false, ForceV2Zero = false;
6877
6878   // Attempt to generate the binary blend mask. If an input is zero then
6879   // we can use any lane.
6880   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
6881   unsigned BlendMask = 0;
6882   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6883     int M = Mask[i];
6884     if (M < 0)
6885       continue;
6886     if (M == i)
6887       continue;
6888     if (M == i + Size) {
6889       BlendMask |= 1u << i;
6890       continue;
6891     }
6892     if (Zeroable[i]) {
6893       if (V1IsZero) {
6894         ForceV1Zero = true;
6895         Mask[i] = i;
6896         continue;
6897       }
6898       if (V2IsZero) {
6899         ForceV2Zero = true;
6900         BlendMask |= 1u << i;
6901         Mask[i] = i + Size;
6902         continue;
6903       }
6904     }
6905     return SDValue(); // Shuffled input!
6906   }
6907
6908   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
6909   if (ForceV1Zero)
6910     V1 = getZeroVector(VT, Subtarget, DAG, DL);
6911   if (ForceV2Zero)
6912     V2 = getZeroVector(VT, Subtarget, DAG, DL);
6913
6914   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
6915     unsigned ScaledMask = 0;
6916     for (int i = 0; i != Size; ++i)
6917       if (BlendMask & (1u << i))
6918         for (int j = 0; j != Scale; ++j)
6919           ScaledMask |= 1u << (i * Scale + j);
6920     return ScaledMask;
6921   };
6922
6923   switch (VT.SimpleTy) {
6924   case MVT::v2f64:
6925   case MVT::v4f32:
6926   case MVT::v4f64:
6927   case MVT::v8f32:
6928     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6929                        DAG.getConstant(BlendMask, DL, MVT::i8));
6930
6931   case MVT::v4i64:
6932   case MVT::v8i32:
6933     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6934     // FALLTHROUGH
6935   case MVT::v2i64:
6936   case MVT::v4i32:
6937     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6938     // that instruction.
6939     if (Subtarget->hasAVX2()) {
6940       // Scale the blend by the number of 32-bit dwords per element.
6941       int Scale =  VT.getScalarSizeInBits() / 32;
6942       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6943       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6944       V1 = DAG.getBitcast(BlendVT, V1);
6945       V2 = DAG.getBitcast(BlendVT, V2);
6946       return DAG.getBitcast(
6947           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6948                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6949     }
6950     // FALLTHROUGH
6951   case MVT::v8i16: {
6952     // For integer shuffles we need to expand the mask and cast the inputs to
6953     // v8i16s prior to blending.
6954     int Scale = 8 / VT.getVectorNumElements();
6955     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6956     V1 = DAG.getBitcast(MVT::v8i16, V1);
6957     V2 = DAG.getBitcast(MVT::v8i16, V2);
6958     return DAG.getBitcast(VT,
6959                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6960                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6961   }
6962
6963   case MVT::v16i16: {
6964     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6965     SmallVector<int, 8> RepeatedMask;
6966     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6967       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6968       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6969       BlendMask = 0;
6970       for (int i = 0; i < 8; ++i)
6971         if (RepeatedMask[i] >= 16)
6972           BlendMask |= 1u << i;
6973       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6974                          DAG.getConstant(BlendMask, DL, MVT::i8));
6975     }
6976   }
6977     // FALLTHROUGH
6978   case MVT::v16i8:
6979   case MVT::v32i8: {
6980     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
6981            "256-bit byte-blends require AVX2 support!");
6982
6983     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6984     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6985       return Masked;
6986
6987     // Scale the blend by the number of bytes per element.
6988     int Scale = VT.getScalarSizeInBits() / 8;
6989
6990     // This form of blend is always done on bytes. Compute the byte vector
6991     // type.
6992     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6993
6994     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6995     // mix of LLVM's code generator and the x86 backend. We tell the code
6996     // generator that boolean values in the elements of an x86 vector register
6997     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6998     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6999     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7000     // of the element (the remaining are ignored) and 0 in that high bit would
7001     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7002     // the LLVM model for boolean values in vector elements gets the relevant
7003     // bit set, it is set backwards and over constrained relative to x86's
7004     // actual model.
7005     SmallVector<SDValue, 32> VSELECTMask;
7006     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7007       for (int j = 0; j < Scale; ++j)
7008         VSELECTMask.push_back(
7009             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7010                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7011                                           MVT::i8));
7012
7013     V1 = DAG.getBitcast(BlendVT, V1);
7014     V2 = DAG.getBitcast(BlendVT, V2);
7015     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7016                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7017                                                       BlendVT, VSELECTMask),
7018                                           V1, V2));
7019   }
7020
7021   default:
7022     llvm_unreachable("Not a supported integer vector type!");
7023   }
7024 }
7025
7026 /// \brief Try to lower as a blend of elements from two inputs followed by
7027 /// a single-input permutation.
7028 ///
7029 /// This matches the pattern where we can blend elements from two inputs and
7030 /// then reduce the shuffle to a single-input permutation.
7031 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7032                                                    SDValue V2,
7033                                                    ArrayRef<int> Mask,
7034                                                    SelectionDAG &DAG) {
7035   // We build up the blend mask while checking whether a blend is a viable way
7036   // to reduce the shuffle.
7037   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7038   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7039
7040   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7041     if (Mask[i] < 0)
7042       continue;
7043
7044     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7045
7046     if (BlendMask[Mask[i] % Size] == -1)
7047       BlendMask[Mask[i] % Size] = Mask[i];
7048     else if (BlendMask[Mask[i] % Size] != Mask[i])
7049       return SDValue(); // Can't blend in the needed input!
7050
7051     PermuteMask[i] = Mask[i] % Size;
7052   }
7053
7054   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7055   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7056 }
7057
7058 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7059 /// blends and permutes.
7060 ///
7061 /// This matches the extremely common pattern for handling combined
7062 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7063 /// operations. It will try to pick the best arrangement of shuffles and
7064 /// blends.
7065 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7066                                                           SDValue V1,
7067                                                           SDValue V2,
7068                                                           ArrayRef<int> Mask,
7069                                                           SelectionDAG &DAG) {
7070   // Shuffle the input elements into the desired positions in V1 and V2 and
7071   // blend them together.
7072   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7073   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7074   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7075   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7076     if (Mask[i] >= 0 && Mask[i] < Size) {
7077       V1Mask[i] = Mask[i];
7078       BlendMask[i] = i;
7079     } else if (Mask[i] >= Size) {
7080       V2Mask[i] = Mask[i] - Size;
7081       BlendMask[i] = i + Size;
7082     }
7083
7084   // Try to lower with the simpler initial blend strategy unless one of the
7085   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7086   // shuffle may be able to fold with a load or other benefit. However, when
7087   // we'll have to do 2x as many shuffles in order to achieve this, blending
7088   // first is a better strategy.
7089   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7090     if (SDValue BlendPerm =
7091             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7092       return BlendPerm;
7093
7094   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7095   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7096   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7097 }
7098
7099 /// \brief Try to lower a vector shuffle as a byte rotation.
7100 ///
7101 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7102 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7103 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7104 /// try to generically lower a vector shuffle through such an pattern. It
7105 /// does not check for the profitability of lowering either as PALIGNR or
7106 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7107 /// This matches shuffle vectors that look like:
7108 ///
7109 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7110 ///
7111 /// Essentially it concatenates V1 and V2, shifts right by some number of
7112 /// elements, and takes the low elements as the result. Note that while this is
7113 /// specified as a *right shift* because x86 is little-endian, it is a *left
7114 /// rotate* of the vector lanes.
7115 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7116                                               SDValue V2,
7117                                               ArrayRef<int> Mask,
7118                                               const X86Subtarget *Subtarget,
7119                                               SelectionDAG &DAG) {
7120   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7121
7122   int NumElts = Mask.size();
7123   int NumLanes = VT.getSizeInBits() / 128;
7124   int NumLaneElts = NumElts / NumLanes;
7125
7126   // We need to detect various ways of spelling a rotation:
7127   //   [11, 12, 13, 14, 15,  0,  1,  2]
7128   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7129   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7130   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7131   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7132   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7133   int Rotation = 0;
7134   SDValue Lo, Hi;
7135   for (int l = 0; l < NumElts; l += NumLaneElts) {
7136     for (int i = 0; i < NumLaneElts; ++i) {
7137       if (Mask[l + i] == -1)
7138         continue;
7139       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7140
7141       // Get the mod-Size index and lane correct it.
7142       int LaneIdx = (Mask[l + i] % NumElts) - l;
7143       // Make sure it was in this lane.
7144       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7145         return SDValue();
7146
7147       // Determine where a rotated vector would have started.
7148       int StartIdx = i - LaneIdx;
7149       if (StartIdx == 0)
7150         // The identity rotation isn't interesting, stop.
7151         return SDValue();
7152
7153       // If we found the tail of a vector the rotation must be the missing
7154       // front. If we found the head of a vector, it must be how much of the
7155       // head.
7156       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7157
7158       if (Rotation == 0)
7159         Rotation = CandidateRotation;
7160       else if (Rotation != CandidateRotation)
7161         // The rotations don't match, so we can't match this mask.
7162         return SDValue();
7163
7164       // Compute which value this mask is pointing at.
7165       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7166
7167       // Compute which of the two target values this index should be assigned
7168       // to. This reflects whether the high elements are remaining or the low
7169       // elements are remaining.
7170       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7171
7172       // Either set up this value if we've not encountered it before, or check
7173       // that it remains consistent.
7174       if (!TargetV)
7175         TargetV = MaskV;
7176       else if (TargetV != MaskV)
7177         // This may be a rotation, but it pulls from the inputs in some
7178         // unsupported interleaving.
7179         return SDValue();
7180     }
7181   }
7182
7183   // Check that we successfully analyzed the mask, and normalize the results.
7184   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7185   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7186   if (!Lo)
7187     Lo = Hi;
7188   else if (!Hi)
7189     Hi = Lo;
7190
7191   // The actual rotate instruction rotates bytes, so we need to scale the
7192   // rotation based on how many bytes are in the vector lane.
7193   int Scale = 16 / NumLaneElts;
7194
7195   // SSSE3 targets can use the palignr instruction.
7196   if (Subtarget->hasSSSE3()) {
7197     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7198     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7199     Lo = DAG.getBitcast(AlignVT, Lo);
7200     Hi = DAG.getBitcast(AlignVT, Hi);
7201
7202     return DAG.getBitcast(
7203         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7204                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7205   }
7206
7207   assert(VT.is128BitVector() &&
7208          "Rotate-based lowering only supports 128-bit lowering!");
7209   assert(Mask.size() <= 16 &&
7210          "Can shuffle at most 16 bytes in a 128-bit vector!");
7211
7212   // Default SSE2 implementation
7213   int LoByteShift = 16 - Rotation * Scale;
7214   int HiByteShift = Rotation * Scale;
7215
7216   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7217   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7218   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7219
7220   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7221                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7222   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7223                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7224   return DAG.getBitcast(VT,
7225                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7226 }
7227
7228 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7229 ///
7230 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7231 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7232 /// matches elements from one of the input vectors shuffled to the left or
7233 /// right with zeroable elements 'shifted in'. It handles both the strictly
7234 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7235 /// quad word lane.
7236 ///
7237 /// PSHL : (little-endian) left bit shift.
7238 /// [ zz, 0, zz,  2 ]
7239 /// [ -1, 4, zz, -1 ]
7240 /// PSRL : (little-endian) right bit shift.
7241 /// [  1, zz,  3, zz]
7242 /// [ -1, -1,  7, zz]
7243 /// PSLLDQ : (little-endian) left byte shift
7244 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7245 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7246 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7247 /// PSRLDQ : (little-endian) right byte shift
7248 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7249 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7250 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7251 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7252                                          SDValue V2, ArrayRef<int> Mask,
7253                                          SelectionDAG &DAG) {
7254   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7255
7256   int Size = Mask.size();
7257   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7258
7259   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7260     for (int i = 0; i < Size; i += Scale)
7261       for (int j = 0; j < Shift; ++j)
7262         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7263           return false;
7264
7265     return true;
7266   };
7267
7268   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7269     for (int i = 0; i != Size; i += Scale) {
7270       unsigned Pos = Left ? i + Shift : i;
7271       unsigned Low = Left ? i : i + Shift;
7272       unsigned Len = Scale - Shift;
7273       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7274                                       Low + (V == V1 ? 0 : Size)))
7275         return SDValue();
7276     }
7277
7278     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7279     bool ByteShift = ShiftEltBits > 64;
7280     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7281                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7282     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7283
7284     // Normalize the scale for byte shifts to still produce an i64 element
7285     // type.
7286     Scale = ByteShift ? Scale / 2 : Scale;
7287
7288     // We need to round trip through the appropriate type for the shift.
7289     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7290     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7291     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7292            "Illegal integer vector type");
7293     V = DAG.getBitcast(ShiftVT, V);
7294
7295     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7296                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7297     return DAG.getBitcast(VT, V);
7298   };
7299
7300   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7301   // keep doubling the size of the integer elements up to that. We can
7302   // then shift the elements of the integer vector by whole multiples of
7303   // their width within the elements of the larger integer vector. Test each
7304   // multiple to see if we can find a match with the moved element indices
7305   // and that the shifted in elements are all zeroable.
7306   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7307     for (int Shift = 1; Shift != Scale; ++Shift)
7308       for (bool Left : {true, false})
7309         if (CheckZeros(Shift, Scale, Left))
7310           for (SDValue V : {V1, V2})
7311             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7312               return Match;
7313
7314   // no match
7315   return SDValue();
7316 }
7317
7318 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7319 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7320                                            SDValue V2, ArrayRef<int> Mask,
7321                                            SelectionDAG &DAG) {
7322   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7323   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7324
7325   int Size = Mask.size();
7326   int HalfSize = Size / 2;
7327   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7328
7329   // Upper half must be undefined.
7330   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7331     return SDValue();
7332
7333   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7334   // Remainder of lower half result is zero and upper half is all undef.
7335   auto LowerAsEXTRQ = [&]() {
7336     // Determine the extraction length from the part of the
7337     // lower half that isn't zeroable.
7338     int Len = HalfSize;
7339     for (; Len > 0; --Len)
7340       if (!Zeroable[Len - 1])
7341         break;
7342     assert(Len > 0 && "Zeroable shuffle mask");
7343
7344     // Attempt to match first Len sequential elements from the lower half.
7345     SDValue Src;
7346     int Idx = -1;
7347     for (int i = 0; i != Len; ++i) {
7348       int M = Mask[i];
7349       if (M < 0)
7350         continue;
7351       SDValue &V = (M < Size ? V1 : V2);
7352       M = M % Size;
7353
7354       // All mask elements must be in the lower half.
7355       if (M >= HalfSize)
7356         return SDValue();
7357
7358       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7359         Src = V;
7360         Idx = M - i;
7361         continue;
7362       }
7363       return SDValue();
7364     }
7365
7366     if (Idx < 0)
7367       return SDValue();
7368
7369     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7370     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7371     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7372     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7373                        DAG.getConstant(BitLen, DL, MVT::i8),
7374                        DAG.getConstant(BitIdx, DL, MVT::i8));
7375   };
7376
7377   if (SDValue ExtrQ = LowerAsEXTRQ())
7378     return ExtrQ;
7379
7380   // INSERTQ: Extract lowest Len elements from lower half of second source and
7381   // insert over first source, starting at Idx.
7382   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7383   auto LowerAsInsertQ = [&]() {
7384     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7385       SDValue Base;
7386
7387       // Attempt to match first source from mask before insertion point.
7388       if (isUndefInRange(Mask, 0, Idx)) {
7389         /* EMPTY */
7390       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7391         Base = V1;
7392       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7393         Base = V2;
7394       } else {
7395         continue;
7396       }
7397
7398       // Extend the extraction length looking to match both the insertion of
7399       // the second source and the remaining elements of the first.
7400       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7401         SDValue Insert;
7402         int Len = Hi - Idx;
7403
7404         // Match insertion.
7405         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7406           Insert = V1;
7407         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7408           Insert = V2;
7409         } else {
7410           continue;
7411         }
7412
7413         // Match the remaining elements of the lower half.
7414         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7415           /* EMPTY */
7416         } else if ((!Base || (Base == V1)) &&
7417                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7418           Base = V1;
7419         } else if ((!Base || (Base == V2)) &&
7420                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7421                                               Size + Hi)) {
7422           Base = V2;
7423         } else {
7424           continue;
7425         }
7426
7427         // We may not have a base (first source) - this can safely be undefined.
7428         if (!Base)
7429           Base = DAG.getUNDEF(VT);
7430
7431         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7432         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7433         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7434                            DAG.getConstant(BitLen, DL, MVT::i8),
7435                            DAG.getConstant(BitIdx, DL, MVT::i8));
7436       }
7437     }
7438
7439     return SDValue();
7440   };
7441
7442   if (SDValue InsertQ = LowerAsInsertQ())
7443     return InsertQ;
7444
7445   return SDValue();
7446 }
7447
7448 /// \brief Lower a vector shuffle as a zero or any extension.
7449 ///
7450 /// Given a specific number of elements, element bit width, and extension
7451 /// stride, produce either a zero or any extension based on the available
7452 /// features of the subtarget. The extended elements are consecutive and
7453 /// begin and can start from an offseted element index in the input; to
7454 /// avoid excess shuffling the offset must either being in the bottom lane
7455 /// or at the start of a higher lane. All extended elements must be from
7456 /// the same lane.
7457 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7458     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7459     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7460   assert(Scale > 1 && "Need a scale to extend.");
7461   int EltBits = VT.getScalarSizeInBits();
7462   int NumElements = VT.getVectorNumElements();
7463   int NumEltsPerLane = 128 / EltBits;
7464   int OffsetLane = Offset / NumEltsPerLane;
7465   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7466          "Only 8, 16, and 32 bit elements can be extended.");
7467   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7468   assert(0 <= Offset && "Extension offset must be positive.");
7469   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7470          "Extension offset must be in the first lane or start an upper lane.");
7471
7472   // Check that an index is in same lane as the base offset.
7473   auto SafeOffset = [&](int Idx) {
7474     return OffsetLane == (Idx / NumEltsPerLane);
7475   };
7476
7477   // Shift along an input so that the offset base moves to the first element.
7478   auto ShuffleOffset = [&](SDValue V) {
7479     if (!Offset)
7480       return V;
7481
7482     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7483     for (int i = 0; i * Scale < NumElements; ++i) {
7484       int SrcIdx = i + Offset;
7485       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7486     }
7487     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7488   };
7489
7490   // Found a valid zext mask! Try various lowering strategies based on the
7491   // input type and available ISA extensions.
7492   if (Subtarget->hasSSE41()) {
7493     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7494     // PUNPCK will catch this in a later shuffle match.
7495     if (Offset && Scale == 2 && VT.is128BitVector())
7496       return SDValue();
7497     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7498                                  NumElements / Scale);
7499     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7500     return DAG.getBitcast(VT, InputV);
7501   }
7502
7503   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7504
7505   // For any extends we can cheat for larger element sizes and use shuffle
7506   // instructions that can fold with a load and/or copy.
7507   if (AnyExt && EltBits == 32) {
7508     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7509                          -1};
7510     return DAG.getBitcast(
7511         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7512                         DAG.getBitcast(MVT::v4i32, InputV),
7513                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7514   }
7515   if (AnyExt && EltBits == 16 && Scale > 2) {
7516     int PSHUFDMask[4] = {Offset / 2, -1,
7517                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7518     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7519                          DAG.getBitcast(MVT::v4i32, InputV),
7520                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7521     int PSHUFWMask[4] = {1, -1, -1, -1};
7522     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7523     return DAG.getBitcast(
7524         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7525                         DAG.getBitcast(MVT::v8i16, InputV),
7526                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7527   }
7528
7529   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7530   // to 64-bits.
7531   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7532     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7533     assert(VT.is128BitVector() && "Unexpected vector width!");
7534
7535     int LoIdx = Offset * EltBits;
7536     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7537                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7538                                          DAG.getConstant(EltBits, DL, MVT::i8),
7539                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7540
7541     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7542         !SafeOffset(Offset + 1))
7543       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7544
7545     int HiIdx = (Offset + 1) * EltBits;
7546     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7547                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7548                                          DAG.getConstant(EltBits, DL, MVT::i8),
7549                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7550     return DAG.getNode(ISD::BITCAST, DL, VT,
7551                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7552   }
7553
7554   // If this would require more than 2 unpack instructions to expand, use
7555   // pshufb when available. We can only use more than 2 unpack instructions
7556   // when zero extending i8 elements which also makes it easier to use pshufb.
7557   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7558     assert(NumElements == 16 && "Unexpected byte vector width!");
7559     SDValue PSHUFBMask[16];
7560     for (int i = 0; i < 16; ++i) {
7561       int Idx = Offset + (i / Scale);
7562       PSHUFBMask[i] = DAG.getConstant(
7563           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7564     }
7565     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7566     return DAG.getBitcast(VT,
7567                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7568                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7569                                                   MVT::v16i8, PSHUFBMask)));
7570   }
7571
7572   // If we are extending from an offset, ensure we start on a boundary that
7573   // we can unpack from.
7574   int AlignToUnpack = Offset % (NumElements / Scale);
7575   if (AlignToUnpack) {
7576     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7577     for (int i = AlignToUnpack; i < NumElements; ++i)
7578       ShMask[i - AlignToUnpack] = i;
7579     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7580     Offset -= AlignToUnpack;
7581   }
7582
7583   // Otherwise emit a sequence of unpacks.
7584   do {
7585     unsigned UnpackLoHi = X86ISD::UNPCKL;
7586     if (Offset >= (NumElements / 2)) {
7587       UnpackLoHi = X86ISD::UNPCKH;
7588       Offset -= (NumElements / 2);
7589     }
7590
7591     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7592     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7593                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7594     InputV = DAG.getBitcast(InputVT, InputV);
7595     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7596     Scale /= 2;
7597     EltBits *= 2;
7598     NumElements /= 2;
7599   } while (Scale > 1);
7600   return DAG.getBitcast(VT, InputV);
7601 }
7602
7603 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7604 ///
7605 /// This routine will try to do everything in its power to cleverly lower
7606 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7607 /// check for the profitability of this lowering,  it tries to aggressively
7608 /// match this pattern. It will use all of the micro-architectural details it
7609 /// can to emit an efficient lowering. It handles both blends with all-zero
7610 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7611 /// masking out later).
7612 ///
7613 /// The reason we have dedicated lowering for zext-style shuffles is that they
7614 /// are both incredibly common and often quite performance sensitive.
7615 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7616     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7617     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7618   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7619
7620   int Bits = VT.getSizeInBits();
7621   int NumLanes = Bits / 128;
7622   int NumElements = VT.getVectorNumElements();
7623   int NumEltsPerLane = NumElements / NumLanes;
7624   assert(VT.getScalarSizeInBits() <= 32 &&
7625          "Exceeds 32-bit integer zero extension limit");
7626   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7627
7628   // Define a helper function to check a particular ext-scale and lower to it if
7629   // valid.
7630   auto Lower = [&](int Scale) -> SDValue {
7631     SDValue InputV;
7632     bool AnyExt = true;
7633     int Offset = 0;
7634     int Matches = 0;
7635     for (int i = 0; i < NumElements; ++i) {
7636       int M = Mask[i];
7637       if (M == -1)
7638         continue; // Valid anywhere but doesn't tell us anything.
7639       if (i % Scale != 0) {
7640         // Each of the extended elements need to be zeroable.
7641         if (!Zeroable[i])
7642           return SDValue();
7643
7644         // We no longer are in the anyext case.
7645         AnyExt = false;
7646         continue;
7647       }
7648
7649       // Each of the base elements needs to be consecutive indices into the
7650       // same input vector.
7651       SDValue V = M < NumElements ? V1 : V2;
7652       M = M % NumElements;
7653       if (!InputV) {
7654         InputV = V;
7655         Offset = M - (i / Scale);
7656       } else if (InputV != V)
7657         return SDValue(); // Flip-flopping inputs.
7658
7659       // Offset must start in the lowest 128-bit lane or at the start of an
7660       // upper lane.
7661       // FIXME: Is it ever worth allowing a negative base offset?
7662       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7663             (Offset % NumEltsPerLane) == 0))
7664         return SDValue();
7665
7666       // If we are offsetting, all referenced entries must come from the same
7667       // lane.
7668       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7669         return SDValue();
7670
7671       if ((M % NumElements) != (Offset + (i / Scale)))
7672         return SDValue(); // Non-consecutive strided elements.
7673       Matches++;
7674     }
7675
7676     // If we fail to find an input, we have a zero-shuffle which should always
7677     // have already been handled.
7678     // FIXME: Maybe handle this here in case during blending we end up with one?
7679     if (!InputV)
7680       return SDValue();
7681
7682     // If we are offsetting, don't extend if we only match a single input, we
7683     // can always do better by using a basic PSHUF or PUNPCK.
7684     if (Offset != 0 && Matches < 2)
7685       return SDValue();
7686
7687     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7688         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7689   };
7690
7691   // The widest scale possible for extending is to a 64-bit integer.
7692   assert(Bits % 64 == 0 &&
7693          "The number of bits in a vector must be divisible by 64 on x86!");
7694   int NumExtElements = Bits / 64;
7695
7696   // Each iteration, try extending the elements half as much, but into twice as
7697   // many elements.
7698   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7699     assert(NumElements % NumExtElements == 0 &&
7700            "The input vector size must be divisible by the extended size.");
7701     if (SDValue V = Lower(NumElements / NumExtElements))
7702       return V;
7703   }
7704
7705   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7706   if (Bits != 128)
7707     return SDValue();
7708
7709   // Returns one of the source operands if the shuffle can be reduced to a
7710   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7711   auto CanZExtLowHalf = [&]() {
7712     for (int i = NumElements / 2; i != NumElements; ++i)
7713       if (!Zeroable[i])
7714         return SDValue();
7715     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7716       return V1;
7717     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7718       return V2;
7719     return SDValue();
7720   };
7721
7722   if (SDValue V = CanZExtLowHalf()) {
7723     V = DAG.getBitcast(MVT::v2i64, V);
7724     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7725     return DAG.getBitcast(VT, V);
7726   }
7727
7728   // No viable ext lowering found.
7729   return SDValue();
7730 }
7731
7732 /// \brief Try to get a scalar value for a specific element of a vector.
7733 ///
7734 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7735 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7736                                               SelectionDAG &DAG) {
7737   MVT VT = V.getSimpleValueType();
7738   MVT EltVT = VT.getVectorElementType();
7739   while (V.getOpcode() == ISD::BITCAST)
7740     V = V.getOperand(0);
7741   // If the bitcasts shift the element size, we can't extract an equivalent
7742   // element from it.
7743   MVT NewVT = V.getSimpleValueType();
7744   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7745     return SDValue();
7746
7747   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7748       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7749     // Ensure the scalar operand is the same size as the destination.
7750     // FIXME: Add support for scalar truncation where possible.
7751     SDValue S = V.getOperand(Idx);
7752     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7753       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7754   }
7755
7756   return SDValue();
7757 }
7758
7759 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7760 ///
7761 /// This is particularly important because the set of instructions varies
7762 /// significantly based on whether the operand is a load or not.
7763 static bool isShuffleFoldableLoad(SDValue V) {
7764   while (V.getOpcode() == ISD::BITCAST)
7765     V = V.getOperand(0);
7766
7767   return ISD::isNON_EXTLoad(V.getNode());
7768 }
7769
7770 /// \brief Try to lower insertion of a single element into a zero vector.
7771 ///
7772 /// This is a common pattern that we have especially efficient patterns to lower
7773 /// across all subtarget feature sets.
7774 static SDValue lowerVectorShuffleAsElementInsertion(
7775     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7776     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7777   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7778   MVT ExtVT = VT;
7779   MVT EltVT = VT.getVectorElementType();
7780
7781   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7782                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7783                 Mask.begin();
7784   bool IsV1Zeroable = true;
7785   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7786     if (i != V2Index && !Zeroable[i]) {
7787       IsV1Zeroable = false;
7788       break;
7789     }
7790
7791   // Check for a single input from a SCALAR_TO_VECTOR node.
7792   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7793   // all the smarts here sunk into that routine. However, the current
7794   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7795   // vector shuffle lowering is dead.
7796   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7797                                                DAG);
7798   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7799     // We need to zext the scalar if it is smaller than an i32.
7800     V2S = DAG.getBitcast(EltVT, V2S);
7801     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7802       // Using zext to expand a narrow element won't work for non-zero
7803       // insertions.
7804       if (!IsV1Zeroable)
7805         return SDValue();
7806
7807       // Zero-extend directly to i32.
7808       ExtVT = MVT::v4i32;
7809       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7810     }
7811     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7812   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7813              EltVT == MVT::i16) {
7814     // Either not inserting from the low element of the input or the input
7815     // element size is too small to use VZEXT_MOVL to clear the high bits.
7816     return SDValue();
7817   }
7818
7819   if (!IsV1Zeroable) {
7820     // If V1 can't be treated as a zero vector we have fewer options to lower
7821     // this. We can't support integer vectors or non-zero targets cheaply, and
7822     // the V1 elements can't be permuted in any way.
7823     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7824     if (!VT.isFloatingPoint() || V2Index != 0)
7825       return SDValue();
7826     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7827     V1Mask[V2Index] = -1;
7828     if (!isNoopShuffleMask(V1Mask))
7829       return SDValue();
7830     // This is essentially a special case blend operation, but if we have
7831     // general purpose blend operations, they are always faster. Bail and let
7832     // the rest of the lowering handle these as blends.
7833     if (Subtarget->hasSSE41())
7834       return SDValue();
7835
7836     // Otherwise, use MOVSD or MOVSS.
7837     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7838            "Only two types of floating point element types to handle!");
7839     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7840                        ExtVT, V1, V2);
7841   }
7842
7843   // This lowering only works for the low element with floating point vectors.
7844   if (VT.isFloatingPoint() && V2Index != 0)
7845     return SDValue();
7846
7847   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7848   if (ExtVT != VT)
7849     V2 = DAG.getBitcast(VT, V2);
7850
7851   if (V2Index != 0) {
7852     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7853     // the desired position. Otherwise it is more efficient to do a vector
7854     // shift left. We know that we can do a vector shift left because all
7855     // the inputs are zero.
7856     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7857       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7858       V2Shuffle[V2Index] = 0;
7859       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7860     } else {
7861       V2 = DAG.getBitcast(MVT::v2i64, V2);
7862       V2 = DAG.getNode(
7863           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7864           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7865                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7866                               DAG.getDataLayout(), VT)));
7867       V2 = DAG.getBitcast(VT, V2);
7868     }
7869   }
7870   return V2;
7871 }
7872
7873 /// \brief Try to lower broadcast of a single - truncated - integer element,
7874 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
7875 ///
7876 /// This assumes we have AVX2.
7877 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
7878                                                   int BroadcastIdx,
7879                                                   const X86Subtarget *Subtarget,
7880                                                   SelectionDAG &DAG) {
7881   assert(Subtarget->hasAVX2() &&
7882          "We can only lower integer broadcasts with AVX2!");
7883
7884   EVT EltVT = VT.getVectorElementType();
7885   EVT V0VT = V0.getValueType();
7886
7887   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
7888   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
7889
7890   EVT V0EltVT = V0VT.getVectorElementType();
7891   if (!V0EltVT.isInteger())
7892     return SDValue();
7893
7894   const unsigned EltSize = EltVT.getSizeInBits();
7895   const unsigned V0EltSize = V0EltVT.getSizeInBits();
7896
7897   // This is only a truncation if the original element type is larger.
7898   if (V0EltSize <= EltSize)
7899     return SDValue();
7900
7901   assert(((V0EltSize % EltSize) == 0) &&
7902          "Scalar type sizes must all be powers of 2 on x86!");
7903
7904   const unsigned V0Opc = V0.getOpcode();
7905   const unsigned Scale = V0EltSize / EltSize;
7906   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
7907
7908   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
7909       V0Opc != ISD::BUILD_VECTOR)
7910     return SDValue();
7911
7912   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
7913
7914   // If we're extracting non-least-significant bits, shift so we can truncate.
7915   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
7916   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
7917   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
7918   if (const int OffsetIdx = BroadcastIdx % Scale)
7919     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
7920             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
7921
7922   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
7923                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
7924 }
7925
7926 /// \brief Try to lower broadcast of a single element.
7927 ///
7928 /// For convenience, this code also bundles all of the subtarget feature set
7929 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7930 /// a convenient way to factor it out.
7931 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7932                                              ArrayRef<int> Mask,
7933                                              const X86Subtarget *Subtarget,
7934                                              SelectionDAG &DAG) {
7935   if (!Subtarget->hasAVX())
7936     return SDValue();
7937   if (VT.isInteger() && !Subtarget->hasAVX2())
7938     return SDValue();
7939
7940   // Check that the mask is a broadcast.
7941   int BroadcastIdx = -1;
7942   for (int M : Mask)
7943     if (M >= 0 && BroadcastIdx == -1)
7944       BroadcastIdx = M;
7945     else if (M >= 0 && M != BroadcastIdx)
7946       return SDValue();
7947
7948   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7949                                             "a sorted mask where the broadcast "
7950                                             "comes from V1.");
7951
7952   // Go up the chain of (vector) values to find a scalar load that we can
7953   // combine with the broadcast.
7954   for (;;) {
7955     switch (V.getOpcode()) {
7956     case ISD::CONCAT_VECTORS: {
7957       int OperandSize = Mask.size() / V.getNumOperands();
7958       V = V.getOperand(BroadcastIdx / OperandSize);
7959       BroadcastIdx %= OperandSize;
7960       continue;
7961     }
7962
7963     case ISD::INSERT_SUBVECTOR: {
7964       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7965       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7966       if (!ConstantIdx)
7967         break;
7968
7969       int BeginIdx = (int)ConstantIdx->getZExtValue();
7970       int EndIdx =
7971           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
7972       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7973         BroadcastIdx -= BeginIdx;
7974         V = VInner;
7975       } else {
7976         V = VOuter;
7977       }
7978       continue;
7979     }
7980     }
7981     break;
7982   }
7983
7984   // Check if this is a broadcast of a scalar. We special case lowering
7985   // for scalars so that we can more effectively fold with loads.
7986   // First, look through bitcast: if the original value has a larger element
7987   // type than the shuffle, the broadcast element is in essence truncated.
7988   // Make that explicit to ease folding.
7989   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
7990     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
7991             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
7992       return TruncBroadcast;
7993
7994   // Also check the simpler case, where we can directly reuse the scalar.
7995   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7996       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7997     V = V.getOperand(BroadcastIdx);
7998
7999     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8000     // Only AVX2 has register broadcasts.
8001     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8002       return SDValue();
8003   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8004     // We can't broadcast from a vector register without AVX2, and we can only
8005     // broadcast from the zero-element of a vector register.
8006     return SDValue();
8007   }
8008
8009   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8010 }
8011
8012 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8013 // INSERTPS when the V1 elements are already in the correct locations
8014 // because otherwise we can just always use two SHUFPS instructions which
8015 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8016 // perform INSERTPS if a single V1 element is out of place and all V2
8017 // elements are zeroable.
8018 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8019                                             ArrayRef<int> Mask,
8020                                             SelectionDAG &DAG) {
8021   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8022   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8023   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8024   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8025
8026   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8027
8028   unsigned ZMask = 0;
8029   int V1DstIndex = -1;
8030   int V2DstIndex = -1;
8031   bool V1UsedInPlace = false;
8032
8033   for (int i = 0; i < 4; ++i) {
8034     // Synthesize a zero mask from the zeroable elements (includes undefs).
8035     if (Zeroable[i]) {
8036       ZMask |= 1 << i;
8037       continue;
8038     }
8039
8040     // Flag if we use any V1 inputs in place.
8041     if (i == Mask[i]) {
8042       V1UsedInPlace = true;
8043       continue;
8044     }
8045
8046     // We can only insert a single non-zeroable element.
8047     if (V1DstIndex != -1 || V2DstIndex != -1)
8048       return SDValue();
8049
8050     if (Mask[i] < 4) {
8051       // V1 input out of place for insertion.
8052       V1DstIndex = i;
8053     } else {
8054       // V2 input for insertion.
8055       V2DstIndex = i;
8056     }
8057   }
8058
8059   // Don't bother if we have no (non-zeroable) element for insertion.
8060   if (V1DstIndex == -1 && V2DstIndex == -1)
8061     return SDValue();
8062
8063   // Determine element insertion src/dst indices. The src index is from the
8064   // start of the inserted vector, not the start of the concatenated vector.
8065   unsigned V2SrcIndex = 0;
8066   if (V1DstIndex != -1) {
8067     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8068     // and don't use the original V2 at all.
8069     V2SrcIndex = Mask[V1DstIndex];
8070     V2DstIndex = V1DstIndex;
8071     V2 = V1;
8072   } else {
8073     V2SrcIndex = Mask[V2DstIndex] - 4;
8074   }
8075
8076   // If no V1 inputs are used in place, then the result is created only from
8077   // the zero mask and the V2 insertion - so remove V1 dependency.
8078   if (!V1UsedInPlace)
8079     V1 = DAG.getUNDEF(MVT::v4f32);
8080
8081   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8082   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8083
8084   // Insert the V2 element into the desired position.
8085   SDLoc DL(Op);
8086   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8087                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8088 }
8089
8090 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8091 /// UNPCK instruction.
8092 ///
8093 /// This specifically targets cases where we end up with alternating between
8094 /// the two inputs, and so can permute them into something that feeds a single
8095 /// UNPCK instruction. Note that this routine only targets integer vectors
8096 /// because for floating point vectors we have a generalized SHUFPS lowering
8097 /// strategy that handles everything that doesn't *exactly* match an unpack,
8098 /// making this clever lowering unnecessary.
8099 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8100                                                     SDValue V1, SDValue V2,
8101                                                     ArrayRef<int> Mask,
8102                                                     SelectionDAG &DAG) {
8103   assert(!VT.isFloatingPoint() &&
8104          "This routine only supports integer vectors.");
8105   assert(!isSingleInputShuffleMask(Mask) &&
8106          "This routine should only be used when blending two inputs.");
8107   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8108
8109   int Size = Mask.size();
8110
8111   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8112     return M >= 0 && M % Size < Size / 2;
8113   });
8114   int NumHiInputs = std::count_if(
8115       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8116
8117   bool UnpackLo = NumLoInputs >= NumHiInputs;
8118
8119   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8120     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8121     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8122
8123     for (int i = 0; i < Size; ++i) {
8124       if (Mask[i] < 0)
8125         continue;
8126
8127       // Each element of the unpack contains Scale elements from this mask.
8128       int UnpackIdx = i / Scale;
8129
8130       // We only handle the case where V1 feeds the first slots of the unpack.
8131       // We rely on canonicalization to ensure this is the case.
8132       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8133         return SDValue();
8134
8135       // Setup the mask for this input. The indexing is tricky as we have to
8136       // handle the unpack stride.
8137       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8138       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8139           Mask[i] % Size;
8140     }
8141
8142     // If we will have to shuffle both inputs to use the unpack, check whether
8143     // we can just unpack first and shuffle the result. If so, skip this unpack.
8144     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8145         !isNoopShuffleMask(V2Mask))
8146       return SDValue();
8147
8148     // Shuffle the inputs into place.
8149     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8150     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8151
8152     // Cast the inputs to the type we will use to unpack them.
8153     V1 = DAG.getBitcast(UnpackVT, V1);
8154     V2 = DAG.getBitcast(UnpackVT, V2);
8155
8156     // Unpack the inputs and cast the result back to the desired type.
8157     return DAG.getBitcast(
8158         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8159                         UnpackVT, V1, V2));
8160   };
8161
8162   // We try each unpack from the largest to the smallest to try and find one
8163   // that fits this mask.
8164   int OrigNumElements = VT.getVectorNumElements();
8165   int OrigScalarSize = VT.getScalarSizeInBits();
8166   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8167     int Scale = ScalarSize / OrigScalarSize;
8168     int NumElements = OrigNumElements / Scale;
8169     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8170     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8171       return Unpack;
8172   }
8173
8174   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8175   // initial unpack.
8176   if (NumLoInputs == 0 || NumHiInputs == 0) {
8177     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8178            "We have to have *some* inputs!");
8179     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8180
8181     // FIXME: We could consider the total complexity of the permute of each
8182     // possible unpacking. Or at the least we should consider how many
8183     // half-crossings are created.
8184     // FIXME: We could consider commuting the unpacks.
8185
8186     SmallVector<int, 32> PermMask;
8187     PermMask.assign(Size, -1);
8188     for (int i = 0; i < Size; ++i) {
8189       if (Mask[i] < 0)
8190         continue;
8191
8192       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8193
8194       PermMask[i] =
8195           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8196     }
8197     return DAG.getVectorShuffle(
8198         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8199                             DL, VT, V1, V2),
8200         DAG.getUNDEF(VT), PermMask);
8201   }
8202
8203   return SDValue();
8204 }
8205
8206 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8207 ///
8208 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8209 /// support for floating point shuffles but not integer shuffles. These
8210 /// instructions will incur a domain crossing penalty on some chips though so
8211 /// it is better to avoid lowering through this for integer vectors where
8212 /// possible.
8213 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8214                                        const X86Subtarget *Subtarget,
8215                                        SelectionDAG &DAG) {
8216   SDLoc DL(Op);
8217   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8218   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8219   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8220   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8221   ArrayRef<int> Mask = SVOp->getMask();
8222   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8223
8224   if (isSingleInputShuffleMask(Mask)) {
8225     // Use low duplicate instructions for masks that match their pattern.
8226     if (Subtarget->hasSSE3())
8227       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8228         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8229
8230     // Straight shuffle of a single input vector. Simulate this by using the
8231     // single input as both of the "inputs" to this instruction..
8232     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8233
8234     if (Subtarget->hasAVX()) {
8235       // If we have AVX, we can use VPERMILPS which will allow folding a load
8236       // into the shuffle.
8237       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8238                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8239     }
8240
8241     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8242                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8243   }
8244   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8245   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8246
8247   // If we have a single input, insert that into V1 if we can do so cheaply.
8248   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8249     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8250             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8251       return Insertion;
8252     // Try inverting the insertion since for v2 masks it is easy to do and we
8253     // can't reliably sort the mask one way or the other.
8254     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8255                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8256     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8257             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8258       return Insertion;
8259   }
8260
8261   // Try to use one of the special instruction patterns to handle two common
8262   // blend patterns if a zero-blend above didn't work.
8263   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8264       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8265     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8266       // We can either use a special instruction to load over the low double or
8267       // to move just the low double.
8268       return DAG.getNode(
8269           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8270           DL, MVT::v2f64, V2,
8271           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8272
8273   if (Subtarget->hasSSE41())
8274     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8275                                                   Subtarget, DAG))
8276       return Blend;
8277
8278   // Use dedicated unpack instructions for masks that match their pattern.
8279   if (SDValue V =
8280           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8281     return V;
8282
8283   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8284   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8285                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8286 }
8287
8288 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8289 ///
8290 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8291 /// the integer unit to minimize domain crossing penalties. However, for blends
8292 /// it falls back to the floating point shuffle operation with appropriate bit
8293 /// casting.
8294 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8295                                        const X86Subtarget *Subtarget,
8296                                        SelectionDAG &DAG) {
8297   SDLoc DL(Op);
8298   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8299   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8300   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8302   ArrayRef<int> Mask = SVOp->getMask();
8303   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8304
8305   if (isSingleInputShuffleMask(Mask)) {
8306     // Check for being able to broadcast a single element.
8307     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8308                                                           Mask, Subtarget, DAG))
8309       return Broadcast;
8310
8311     // Straight shuffle of a single input vector. For everything from SSE2
8312     // onward this has a single fast instruction with no scary immediates.
8313     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8314     V1 = DAG.getBitcast(MVT::v4i32, V1);
8315     int WidenedMask[4] = {
8316         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8317         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8318     return DAG.getBitcast(
8319         MVT::v2i64,
8320         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8321                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8322   }
8323   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8324   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8325   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8326   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8327
8328   // If we have a blend of two PACKUS operations an the blend aligns with the
8329   // low and half halves, we can just merge the PACKUS operations. This is
8330   // particularly important as it lets us merge shuffles that this routine itself
8331   // creates.
8332   auto GetPackNode = [](SDValue V) {
8333     while (V.getOpcode() == ISD::BITCAST)
8334       V = V.getOperand(0);
8335
8336     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8337   };
8338   if (SDValue V1Pack = GetPackNode(V1))
8339     if (SDValue V2Pack = GetPackNode(V2))
8340       return DAG.getBitcast(MVT::v2i64,
8341                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8342                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8343                                                      : V1Pack.getOperand(1),
8344                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8345                                                      : V2Pack.getOperand(1)));
8346
8347   // Try to use shift instructions.
8348   if (SDValue Shift =
8349           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8350     return Shift;
8351
8352   // When loading a scalar and then shuffling it into a vector we can often do
8353   // the insertion cheaply.
8354   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8355           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8356     return Insertion;
8357   // Try inverting the insertion since for v2 masks it is easy to do and we
8358   // can't reliably sort the mask one way or the other.
8359   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8360   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8361           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8362     return Insertion;
8363
8364   // We have different paths for blend lowering, but they all must use the
8365   // *exact* same predicate.
8366   bool IsBlendSupported = Subtarget->hasSSE41();
8367   if (IsBlendSupported)
8368     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8369                                                   Subtarget, DAG))
8370       return Blend;
8371
8372   // Use dedicated unpack instructions for masks that match their pattern.
8373   if (SDValue V =
8374           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8375     return V;
8376
8377   // Try to use byte rotation instructions.
8378   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8379   if (Subtarget->hasSSSE3())
8380     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8381             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8382       return Rotate;
8383
8384   // If we have direct support for blends, we should lower by decomposing into
8385   // a permute. That will be faster than the domain cross.
8386   if (IsBlendSupported)
8387     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8388                                                       Mask, DAG);
8389
8390   // We implement this with SHUFPD which is pretty lame because it will likely
8391   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8392   // However, all the alternatives are still more cycles and newer chips don't
8393   // have this problem. It would be really nice if x86 had better shuffles here.
8394   V1 = DAG.getBitcast(MVT::v2f64, V1);
8395   V2 = DAG.getBitcast(MVT::v2f64, V2);
8396   return DAG.getBitcast(MVT::v2i64,
8397                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8398 }
8399
8400 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8401 ///
8402 /// This is used to disable more specialized lowerings when the shufps lowering
8403 /// will happen to be efficient.
8404 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8405   // This routine only handles 128-bit shufps.
8406   assert(Mask.size() == 4 && "Unsupported mask size!");
8407
8408   // To lower with a single SHUFPS we need to have the low half and high half
8409   // each requiring a single input.
8410   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8411     return false;
8412   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8413     return false;
8414
8415   return true;
8416 }
8417
8418 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8419 ///
8420 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8421 /// It makes no assumptions about whether this is the *best* lowering, it simply
8422 /// uses it.
8423 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8424                                             ArrayRef<int> Mask, SDValue V1,
8425                                             SDValue V2, SelectionDAG &DAG) {
8426   SDValue LowV = V1, HighV = V2;
8427   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8428
8429   int NumV2Elements =
8430       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8431
8432   if (NumV2Elements == 1) {
8433     int V2Index =
8434         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8435         Mask.begin();
8436
8437     // Compute the index adjacent to V2Index and in the same half by toggling
8438     // the low bit.
8439     int V2AdjIndex = V2Index ^ 1;
8440
8441     if (Mask[V2AdjIndex] == -1) {
8442       // Handles all the cases where we have a single V2 element and an undef.
8443       // This will only ever happen in the high lanes because we commute the
8444       // vector otherwise.
8445       if (V2Index < 2)
8446         std::swap(LowV, HighV);
8447       NewMask[V2Index] -= 4;
8448     } else {
8449       // Handle the case where the V2 element ends up adjacent to a V1 element.
8450       // To make this work, blend them together as the first step.
8451       int V1Index = V2AdjIndex;
8452       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8453       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8454                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8455
8456       // Now proceed to reconstruct the final blend as we have the necessary
8457       // high or low half formed.
8458       if (V2Index < 2) {
8459         LowV = V2;
8460         HighV = V1;
8461       } else {
8462         HighV = V2;
8463       }
8464       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8465       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8466     }
8467   } else if (NumV2Elements == 2) {
8468     if (Mask[0] < 4 && Mask[1] < 4) {
8469       // Handle the easy case where we have V1 in the low lanes and V2 in the
8470       // high lanes.
8471       NewMask[2] -= 4;
8472       NewMask[3] -= 4;
8473     } else if (Mask[2] < 4 && Mask[3] < 4) {
8474       // We also handle the reversed case because this utility may get called
8475       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8476       // arrange things in the right direction.
8477       NewMask[0] -= 4;
8478       NewMask[1] -= 4;
8479       HighV = V1;
8480       LowV = V2;
8481     } else {
8482       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8483       // trying to place elements directly, just blend them and set up the final
8484       // shuffle to place them.
8485
8486       // The first two blend mask elements are for V1, the second two are for
8487       // V2.
8488       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8489                           Mask[2] < 4 ? Mask[2] : Mask[3],
8490                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8491                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8492       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8493                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8494
8495       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8496       // a blend.
8497       LowV = HighV = V1;
8498       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8499       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8500       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8501       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8502     }
8503   }
8504   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8505                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8506 }
8507
8508 /// \brief Lower 4-lane 32-bit floating point shuffles.
8509 ///
8510 /// Uses instructions exclusively from the floating point unit to minimize
8511 /// domain crossing penalties, as these are sufficient to implement all v4f32
8512 /// shuffles.
8513 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8514                                        const X86Subtarget *Subtarget,
8515                                        SelectionDAG &DAG) {
8516   SDLoc DL(Op);
8517   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8518   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8519   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8521   ArrayRef<int> Mask = SVOp->getMask();
8522   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8523
8524   int NumV2Elements =
8525       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8526
8527   if (NumV2Elements == 0) {
8528     // Check for being able to broadcast a single element.
8529     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8530                                                           Mask, Subtarget, DAG))
8531       return Broadcast;
8532
8533     // Use even/odd duplicate instructions for masks that match their pattern.
8534     if (Subtarget->hasSSE3()) {
8535       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8536         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8537       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8538         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8539     }
8540
8541     if (Subtarget->hasAVX()) {
8542       // If we have AVX, we can use VPERMILPS which will allow folding a load
8543       // into the shuffle.
8544       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8545                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8546     }
8547
8548     // Otherwise, use a straight shuffle of a single input vector. We pass the
8549     // input vector to both operands to simulate this with a SHUFPS.
8550     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8551                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8552   }
8553
8554   // There are special ways we can lower some single-element blends. However, we
8555   // have custom ways we can lower more complex single-element blends below that
8556   // we defer to if both this and BLENDPS fail to match, so restrict this to
8557   // when the V2 input is targeting element 0 of the mask -- that is the fast
8558   // case here.
8559   if (NumV2Elements == 1 && Mask[0] >= 4)
8560     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8561                                                          Mask, Subtarget, DAG))
8562       return V;
8563
8564   if (Subtarget->hasSSE41()) {
8565     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8566                                                   Subtarget, DAG))
8567       return Blend;
8568
8569     // Use INSERTPS if we can complete the shuffle efficiently.
8570     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8571       return V;
8572
8573     if (!isSingleSHUFPSMask(Mask))
8574       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8575               DL, MVT::v4f32, V1, V2, Mask, DAG))
8576         return BlendPerm;
8577   }
8578
8579   // Use dedicated unpack instructions for masks that match their pattern.
8580   if (SDValue V =
8581           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8582     return V;
8583
8584   // Otherwise fall back to a SHUFPS lowering strategy.
8585   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8586 }
8587
8588 /// \brief Lower 4-lane i32 vector shuffles.
8589 ///
8590 /// We try to handle these with integer-domain shuffles where we can, but for
8591 /// blends we use the floating point domain blend instructions.
8592 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8593                                        const X86Subtarget *Subtarget,
8594                                        SelectionDAG &DAG) {
8595   SDLoc DL(Op);
8596   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8597   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8598   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8599   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8600   ArrayRef<int> Mask = SVOp->getMask();
8601   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8602
8603   // Whenever we can lower this as a zext, that instruction is strictly faster
8604   // than any alternative. It also allows us to fold memory operands into the
8605   // shuffle in many cases.
8606   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8607                                                          Mask, Subtarget, DAG))
8608     return ZExt;
8609
8610   int NumV2Elements =
8611       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8612
8613   if (NumV2Elements == 0) {
8614     // Check for being able to broadcast a single element.
8615     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8616                                                           Mask, Subtarget, DAG))
8617       return Broadcast;
8618
8619     // Straight shuffle of a single input vector. For everything from SSE2
8620     // onward this has a single fast instruction with no scary immediates.
8621     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8622     // but we aren't actually going to use the UNPCK instruction because doing
8623     // so prevents folding a load into this instruction or making a copy.
8624     const int UnpackLoMask[] = {0, 0, 1, 1};
8625     const int UnpackHiMask[] = {2, 2, 3, 3};
8626     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8627       Mask = UnpackLoMask;
8628     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8629       Mask = UnpackHiMask;
8630
8631     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8632                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8633   }
8634
8635   // Try to use shift instructions.
8636   if (SDValue Shift =
8637           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8638     return Shift;
8639
8640   // There are special ways we can lower some single-element blends.
8641   if (NumV2Elements == 1)
8642     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8643                                                          Mask, Subtarget, DAG))
8644       return V;
8645
8646   // We have different paths for blend lowering, but they all must use the
8647   // *exact* same predicate.
8648   bool IsBlendSupported = Subtarget->hasSSE41();
8649   if (IsBlendSupported)
8650     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8651                                                   Subtarget, DAG))
8652       return Blend;
8653
8654   if (SDValue Masked =
8655           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8656     return Masked;
8657
8658   // Use dedicated unpack instructions for masks that match their pattern.
8659   if (SDValue V =
8660           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8661     return V;
8662
8663   // Try to use byte rotation instructions.
8664   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8665   if (Subtarget->hasSSSE3())
8666     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8667             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8668       return Rotate;
8669
8670   // If we have direct support for blends, we should lower by decomposing into
8671   // a permute. That will be faster than the domain cross.
8672   if (IsBlendSupported)
8673     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8674                                                       Mask, DAG);
8675
8676   // Try to lower by permuting the inputs into an unpack instruction.
8677   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8678                                                             V2, Mask, DAG))
8679     return Unpack;
8680
8681   // We implement this with SHUFPS because it can blend from two vectors.
8682   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8683   // up the inputs, bypassing domain shift penalties that we would encur if we
8684   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8685   // relevant.
8686   return DAG.getBitcast(
8687       MVT::v4i32,
8688       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8689                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8690 }
8691
8692 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8693 /// shuffle lowering, and the most complex part.
8694 ///
8695 /// The lowering strategy is to try to form pairs of input lanes which are
8696 /// targeted at the same half of the final vector, and then use a dword shuffle
8697 /// to place them onto the right half, and finally unpack the paired lanes into
8698 /// their final position.
8699 ///
8700 /// The exact breakdown of how to form these dword pairs and align them on the
8701 /// correct sides is really tricky. See the comments within the function for
8702 /// more of the details.
8703 ///
8704 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8705 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8706 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8707 /// vector, form the analogous 128-bit 8-element Mask.
8708 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8709     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8710     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8711   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8712   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8713
8714   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8715   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8716   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8717
8718   SmallVector<int, 4> LoInputs;
8719   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8720                [](int M) { return M >= 0; });
8721   std::sort(LoInputs.begin(), LoInputs.end());
8722   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8723   SmallVector<int, 4> HiInputs;
8724   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8725                [](int M) { return M >= 0; });
8726   std::sort(HiInputs.begin(), HiInputs.end());
8727   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8728   int NumLToL =
8729       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8730   int NumHToL = LoInputs.size() - NumLToL;
8731   int NumLToH =
8732       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8733   int NumHToH = HiInputs.size() - NumLToH;
8734   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8735   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8736   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8737   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8738
8739   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8740   // such inputs we can swap two of the dwords across the half mark and end up
8741   // with <=2 inputs to each half in each half. Once there, we can fall through
8742   // to the generic code below. For example:
8743   //
8744   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8745   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8746   //
8747   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8748   // and an existing 2-into-2 on the other half. In this case we may have to
8749   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8750   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8751   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8752   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8753   // half than the one we target for fixing) will be fixed when we re-enter this
8754   // path. We will also combine away any sequence of PSHUFD instructions that
8755   // result into a single instruction. Here is an example of the tricky case:
8756   //
8757   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8758   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8759   //
8760   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8761   //
8762   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8763   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8764   //
8765   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8766   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8767   //
8768   // The result is fine to be handled by the generic logic.
8769   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8770                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8771                           int AOffset, int BOffset) {
8772     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8773            "Must call this with A having 3 or 1 inputs from the A half.");
8774     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8775            "Must call this with B having 1 or 3 inputs from the B half.");
8776     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8777            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8778
8779     bool ThreeAInputs = AToAInputs.size() == 3;
8780
8781     // Compute the index of dword with only one word among the three inputs in
8782     // a half by taking the sum of the half with three inputs and subtracting
8783     // the sum of the actual three inputs. The difference is the remaining
8784     // slot.
8785     int ADWord, BDWord;
8786     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8787     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8788     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8789     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8790     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8791     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8792     int TripleNonInputIdx =
8793         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8794     TripleDWord = TripleNonInputIdx / 2;
8795
8796     // We use xor with one to compute the adjacent DWord to whichever one the
8797     // OneInput is in.
8798     OneInputDWord = (OneInput / 2) ^ 1;
8799
8800     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8801     // and BToA inputs. If there is also such a problem with the BToB and AToB
8802     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8803     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8804     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8805     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8806       // Compute how many inputs will be flipped by swapping these DWords. We
8807       // need
8808       // to balance this to ensure we don't form a 3-1 shuffle in the other
8809       // half.
8810       int NumFlippedAToBInputs =
8811           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8812           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8813       int NumFlippedBToBInputs =
8814           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8815           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8816       if ((NumFlippedAToBInputs == 1 &&
8817            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8818           (NumFlippedBToBInputs == 1 &&
8819            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8820         // We choose whether to fix the A half or B half based on whether that
8821         // half has zero flipped inputs. At zero, we may not be able to fix it
8822         // with that half. We also bias towards fixing the B half because that
8823         // will more commonly be the high half, and we have to bias one way.
8824         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8825                                                        ArrayRef<int> Inputs) {
8826           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8827           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8828                                          PinnedIdx ^ 1) != Inputs.end();
8829           // Determine whether the free index is in the flipped dword or the
8830           // unflipped dword based on where the pinned index is. We use this bit
8831           // in an xor to conditionally select the adjacent dword.
8832           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8833           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8834                                              FixFreeIdx) != Inputs.end();
8835           if (IsFixIdxInput == IsFixFreeIdxInput)
8836             FixFreeIdx += 1;
8837           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8838                                         FixFreeIdx) != Inputs.end();
8839           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8840                  "We need to be changing the number of flipped inputs!");
8841           int PSHUFHalfMask[] = {0, 1, 2, 3};
8842           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8843           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8844                           MVT::v8i16, V,
8845                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8846
8847           for (int &M : Mask)
8848             if (M != -1 && M == FixIdx)
8849               M = FixFreeIdx;
8850             else if (M != -1 && M == FixFreeIdx)
8851               M = FixIdx;
8852         };
8853         if (NumFlippedBToBInputs != 0) {
8854           int BPinnedIdx =
8855               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8856           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8857         } else {
8858           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8859           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8860           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8861         }
8862       }
8863     }
8864
8865     int PSHUFDMask[] = {0, 1, 2, 3};
8866     PSHUFDMask[ADWord] = BDWord;
8867     PSHUFDMask[BDWord] = ADWord;
8868     V = DAG.getBitcast(
8869         VT,
8870         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8871                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8872
8873     // Adjust the mask to match the new locations of A and B.
8874     for (int &M : Mask)
8875       if (M != -1 && M/2 == ADWord)
8876         M = 2 * BDWord + M % 2;
8877       else if (M != -1 && M/2 == BDWord)
8878         M = 2 * ADWord + M % 2;
8879
8880     // Recurse back into this routine to re-compute state now that this isn't
8881     // a 3 and 1 problem.
8882     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8883                                                      DAG);
8884   };
8885   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8886     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8887   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8888     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8889
8890   // At this point there are at most two inputs to the low and high halves from
8891   // each half. That means the inputs can always be grouped into dwords and
8892   // those dwords can then be moved to the correct half with a dword shuffle.
8893   // We use at most one low and one high word shuffle to collect these paired
8894   // inputs into dwords, and finally a dword shuffle to place them.
8895   int PSHUFLMask[4] = {-1, -1, -1, -1};
8896   int PSHUFHMask[4] = {-1, -1, -1, -1};
8897   int PSHUFDMask[4] = {-1, -1, -1, -1};
8898
8899   // First fix the masks for all the inputs that are staying in their
8900   // original halves. This will then dictate the targets of the cross-half
8901   // shuffles.
8902   auto fixInPlaceInputs =
8903       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8904                     MutableArrayRef<int> SourceHalfMask,
8905                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8906     if (InPlaceInputs.empty())
8907       return;
8908     if (InPlaceInputs.size() == 1) {
8909       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8910           InPlaceInputs[0] - HalfOffset;
8911       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8912       return;
8913     }
8914     if (IncomingInputs.empty()) {
8915       // Just fix all of the in place inputs.
8916       for (int Input : InPlaceInputs) {
8917         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8918         PSHUFDMask[Input / 2] = Input / 2;
8919       }
8920       return;
8921     }
8922
8923     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8924     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8925         InPlaceInputs[0] - HalfOffset;
8926     // Put the second input next to the first so that they are packed into
8927     // a dword. We find the adjacent index by toggling the low bit.
8928     int AdjIndex = InPlaceInputs[0] ^ 1;
8929     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8930     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8931     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8932   };
8933   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8934   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8935
8936   // Now gather the cross-half inputs and place them into a free dword of
8937   // their target half.
8938   // FIXME: This operation could almost certainly be simplified dramatically to
8939   // look more like the 3-1 fixing operation.
8940   auto moveInputsToRightHalf = [&PSHUFDMask](
8941       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8942       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8943       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8944       int DestOffset) {
8945     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8946       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8947     };
8948     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8949                                                int Word) {
8950       int LowWord = Word & ~1;
8951       int HighWord = Word | 1;
8952       return isWordClobbered(SourceHalfMask, LowWord) ||
8953              isWordClobbered(SourceHalfMask, HighWord);
8954     };
8955
8956     if (IncomingInputs.empty())
8957       return;
8958
8959     if (ExistingInputs.empty()) {
8960       // Map any dwords with inputs from them into the right half.
8961       for (int Input : IncomingInputs) {
8962         // If the source half mask maps over the inputs, turn those into
8963         // swaps and use the swapped lane.
8964         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8965           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8966             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8967                 Input - SourceOffset;
8968             // We have to swap the uses in our half mask in one sweep.
8969             for (int &M : HalfMask)
8970               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8971                 M = Input;
8972               else if (M == Input)
8973                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8974           } else {
8975             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8976                        Input - SourceOffset &&
8977                    "Previous placement doesn't match!");
8978           }
8979           // Note that this correctly re-maps both when we do a swap and when
8980           // we observe the other side of the swap above. We rely on that to
8981           // avoid swapping the members of the input list directly.
8982           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8983         }
8984
8985         // Map the input's dword into the correct half.
8986         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8987           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8988         else
8989           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8990                      Input / 2 &&
8991                  "Previous placement doesn't match!");
8992       }
8993
8994       // And just directly shift any other-half mask elements to be same-half
8995       // as we will have mirrored the dword containing the element into the
8996       // same position within that half.
8997       for (int &M : HalfMask)
8998         if (M >= SourceOffset && M < SourceOffset + 4) {
8999           M = M - SourceOffset + DestOffset;
9000           assert(M >= 0 && "This should never wrap below zero!");
9001         }
9002       return;
9003     }
9004
9005     // Ensure we have the input in a viable dword of its current half. This
9006     // is particularly tricky because the original position may be clobbered
9007     // by inputs being moved and *staying* in that half.
9008     if (IncomingInputs.size() == 1) {
9009       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9010         int InputFixed = std::find(std::begin(SourceHalfMask),
9011                                    std::end(SourceHalfMask), -1) -
9012                          std::begin(SourceHalfMask) + SourceOffset;
9013         SourceHalfMask[InputFixed - SourceOffset] =
9014             IncomingInputs[0] - SourceOffset;
9015         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9016                      InputFixed);
9017         IncomingInputs[0] = InputFixed;
9018       }
9019     } else if (IncomingInputs.size() == 2) {
9020       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9021           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9022         // We have two non-adjacent or clobbered inputs we need to extract from
9023         // the source half. To do this, we need to map them into some adjacent
9024         // dword slot in the source mask.
9025         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9026                               IncomingInputs[1] - SourceOffset};
9027
9028         // If there is a free slot in the source half mask adjacent to one of
9029         // the inputs, place the other input in it. We use (Index XOR 1) to
9030         // compute an adjacent index.
9031         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9032             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9033           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9034           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9035           InputsFixed[1] = InputsFixed[0] ^ 1;
9036         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9037                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9038           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9039           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9040           InputsFixed[0] = InputsFixed[1] ^ 1;
9041         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9042                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9043           // The two inputs are in the same DWord but it is clobbered and the
9044           // adjacent DWord isn't used at all. Move both inputs to the free
9045           // slot.
9046           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9047           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9048           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9049           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9050         } else {
9051           // The only way we hit this point is if there is no clobbering
9052           // (because there are no off-half inputs to this half) and there is no
9053           // free slot adjacent to one of the inputs. In this case, we have to
9054           // swap an input with a non-input.
9055           for (int i = 0; i < 4; ++i)
9056             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9057                    "We can't handle any clobbers here!");
9058           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9059                  "Cannot have adjacent inputs here!");
9060
9061           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9062           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9063
9064           // We also have to update the final source mask in this case because
9065           // it may need to undo the above swap.
9066           for (int &M : FinalSourceHalfMask)
9067             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9068               M = InputsFixed[1] + SourceOffset;
9069             else if (M == InputsFixed[1] + SourceOffset)
9070               M = (InputsFixed[0] ^ 1) + SourceOffset;
9071
9072           InputsFixed[1] = InputsFixed[0] ^ 1;
9073         }
9074
9075         // Point everything at the fixed inputs.
9076         for (int &M : HalfMask)
9077           if (M == IncomingInputs[0])
9078             M = InputsFixed[0] + SourceOffset;
9079           else if (M == IncomingInputs[1])
9080             M = InputsFixed[1] + SourceOffset;
9081
9082         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9083         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9084       }
9085     } else {
9086       llvm_unreachable("Unhandled input size!");
9087     }
9088
9089     // Now hoist the DWord down to the right half.
9090     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9091     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9092     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9093     for (int &M : HalfMask)
9094       for (int Input : IncomingInputs)
9095         if (M == Input)
9096           M = FreeDWord * 2 + Input % 2;
9097   };
9098   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9099                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9100   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9101                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9102
9103   // Now enact all the shuffles we've computed to move the inputs into their
9104   // target half.
9105   if (!isNoopShuffleMask(PSHUFLMask))
9106     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9107                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9108   if (!isNoopShuffleMask(PSHUFHMask))
9109     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9110                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9111   if (!isNoopShuffleMask(PSHUFDMask))
9112     V = DAG.getBitcast(
9113         VT,
9114         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9115                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9116
9117   // At this point, each half should contain all its inputs, and we can then
9118   // just shuffle them into their final position.
9119   assert(std::count_if(LoMask.begin(), LoMask.end(),
9120                        [](int M) { return M >= 4; }) == 0 &&
9121          "Failed to lift all the high half inputs to the low mask!");
9122   assert(std::count_if(HiMask.begin(), HiMask.end(),
9123                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9124          "Failed to lift all the low half inputs to the high mask!");
9125
9126   // Do a half shuffle for the low mask.
9127   if (!isNoopShuffleMask(LoMask))
9128     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9129                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9130
9131   // Do a half shuffle with the high mask after shifting its values down.
9132   for (int &M : HiMask)
9133     if (M >= 0)
9134       M -= 4;
9135   if (!isNoopShuffleMask(HiMask))
9136     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9137                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9138
9139   return V;
9140 }
9141
9142 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9143 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9144                                           SDValue V2, ArrayRef<int> Mask,
9145                                           SelectionDAG &DAG, bool &V1InUse,
9146                                           bool &V2InUse) {
9147   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9148   SDValue V1Mask[16];
9149   SDValue V2Mask[16];
9150   V1InUse = false;
9151   V2InUse = false;
9152
9153   int Size = Mask.size();
9154   int Scale = 16 / Size;
9155   for (int i = 0; i < 16; ++i) {
9156     if (Mask[i / Scale] == -1) {
9157       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9158     } else {
9159       const int ZeroMask = 0x80;
9160       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9161                                           : ZeroMask;
9162       int V2Idx = Mask[i / Scale] < Size
9163                       ? ZeroMask
9164                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9165       if (Zeroable[i / Scale])
9166         V1Idx = V2Idx = ZeroMask;
9167       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9168       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9169       V1InUse |= (ZeroMask != V1Idx);
9170       V2InUse |= (ZeroMask != V2Idx);
9171     }
9172   }
9173
9174   if (V1InUse)
9175     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9176                      DAG.getBitcast(MVT::v16i8, V1),
9177                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9178   if (V2InUse)
9179     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9180                      DAG.getBitcast(MVT::v16i8, V2),
9181                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9182
9183   // If we need shuffled inputs from both, blend the two.
9184   SDValue V;
9185   if (V1InUse && V2InUse)
9186     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9187   else
9188     V = V1InUse ? V1 : V2;
9189
9190   // Cast the result back to the correct type.
9191   return DAG.getBitcast(VT, V);
9192 }
9193
9194 /// \brief Generic lowering of 8-lane i16 shuffles.
9195 ///
9196 /// This handles both single-input shuffles and combined shuffle/blends with
9197 /// two inputs. The single input shuffles are immediately delegated to
9198 /// a dedicated lowering routine.
9199 ///
9200 /// The blends are lowered in one of three fundamental ways. If there are few
9201 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9202 /// of the input is significantly cheaper when lowered as an interleaving of
9203 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9204 /// halves of the inputs separately (making them have relatively few inputs)
9205 /// and then concatenate them.
9206 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9207                                        const X86Subtarget *Subtarget,
9208                                        SelectionDAG &DAG) {
9209   SDLoc DL(Op);
9210   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9211   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9212   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9213   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9214   ArrayRef<int> OrigMask = SVOp->getMask();
9215   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9216                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9217   MutableArrayRef<int> Mask(MaskStorage);
9218
9219   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9220
9221   // Whenever we can lower this as a zext, that instruction is strictly faster
9222   // than any alternative.
9223   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9224           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9225     return ZExt;
9226
9227   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9228   (void)isV1;
9229   auto isV2 = [](int M) { return M >= 8; };
9230
9231   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9232
9233   if (NumV2Inputs == 0) {
9234     // Check for being able to broadcast a single element.
9235     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9236                                                           Mask, Subtarget, DAG))
9237       return Broadcast;
9238
9239     // Try to use shift instructions.
9240     if (SDValue Shift =
9241             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9242       return Shift;
9243
9244     // Use dedicated unpack instructions for masks that match their pattern.
9245     if (SDValue V =
9246             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9247       return V;
9248
9249     // Try to use byte rotation instructions.
9250     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9251                                                         Mask, Subtarget, DAG))
9252       return Rotate;
9253
9254     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9255                                                      Subtarget, DAG);
9256   }
9257
9258   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9259          "All single-input shuffles should be canonicalized to be V1-input "
9260          "shuffles.");
9261
9262   // Try to use shift instructions.
9263   if (SDValue Shift =
9264           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9265     return Shift;
9266
9267   // See if we can use SSE4A Extraction / Insertion.
9268   if (Subtarget->hasSSE4A())
9269     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9270       return V;
9271
9272   // There are special ways we can lower some single-element blends.
9273   if (NumV2Inputs == 1)
9274     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9275                                                          Mask, Subtarget, DAG))
9276       return V;
9277
9278   // We have different paths for blend lowering, but they all must use the
9279   // *exact* same predicate.
9280   bool IsBlendSupported = Subtarget->hasSSE41();
9281   if (IsBlendSupported)
9282     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9283                                                   Subtarget, DAG))
9284       return Blend;
9285
9286   if (SDValue Masked =
9287           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9288     return Masked;
9289
9290   // Use dedicated unpack instructions for masks that match their pattern.
9291   if (SDValue V =
9292           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9293     return V;
9294
9295   // Try to use byte rotation instructions.
9296   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9297           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9298     return Rotate;
9299
9300   if (SDValue BitBlend =
9301           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9302     return BitBlend;
9303
9304   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9305                                                             V2, Mask, DAG))
9306     return Unpack;
9307
9308   // If we can't directly blend but can use PSHUFB, that will be better as it
9309   // can both shuffle and set up the inefficient blend.
9310   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9311     bool V1InUse, V2InUse;
9312     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9313                                       V1InUse, V2InUse);
9314   }
9315
9316   // We can always bit-blend if we have to so the fallback strategy is to
9317   // decompose into single-input permutes and blends.
9318   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9319                                                       Mask, DAG);
9320 }
9321
9322 /// \brief Check whether a compaction lowering can be done by dropping even
9323 /// elements and compute how many times even elements must be dropped.
9324 ///
9325 /// This handles shuffles which take every Nth element where N is a power of
9326 /// two. Example shuffle masks:
9327 ///
9328 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9329 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9330 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9331 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9332 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9333 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9334 ///
9335 /// Any of these lanes can of course be undef.
9336 ///
9337 /// This routine only supports N <= 3.
9338 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9339 /// for larger N.
9340 ///
9341 /// \returns N above, or the number of times even elements must be dropped if
9342 /// there is such a number. Otherwise returns zero.
9343 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9344   // Figure out whether we're looping over two inputs or just one.
9345   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9346
9347   // The modulus for the shuffle vector entries is based on whether this is
9348   // a single input or not.
9349   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9350   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9351          "We should only be called with masks with a power-of-2 size!");
9352
9353   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9354
9355   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9356   // and 2^3 simultaneously. This is because we may have ambiguity with
9357   // partially undef inputs.
9358   bool ViableForN[3] = {true, true, true};
9359
9360   for (int i = 0, e = Mask.size(); i < e; ++i) {
9361     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9362     // want.
9363     if (Mask[i] == -1)
9364       continue;
9365
9366     bool IsAnyViable = false;
9367     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9368       if (ViableForN[j]) {
9369         uint64_t N = j + 1;
9370
9371         // The shuffle mask must be equal to (i * 2^N) % M.
9372         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9373           IsAnyViable = true;
9374         else
9375           ViableForN[j] = false;
9376       }
9377     // Early exit if we exhaust the possible powers of two.
9378     if (!IsAnyViable)
9379       break;
9380   }
9381
9382   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9383     if (ViableForN[j])
9384       return j + 1;
9385
9386   // Return 0 as there is no viable power of two.
9387   return 0;
9388 }
9389
9390 /// \brief Generic lowering of v16i8 shuffles.
9391 ///
9392 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9393 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9394 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9395 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9396 /// back together.
9397 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9398                                        const X86Subtarget *Subtarget,
9399                                        SelectionDAG &DAG) {
9400   SDLoc DL(Op);
9401   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9402   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9403   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9404   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9405   ArrayRef<int> Mask = SVOp->getMask();
9406   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9407
9408   // Try to use shift instructions.
9409   if (SDValue Shift =
9410           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9411     return Shift;
9412
9413   // Try to use byte rotation instructions.
9414   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9415           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9416     return Rotate;
9417
9418   // Try to use a zext lowering.
9419   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9420           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9421     return ZExt;
9422
9423   // See if we can use SSE4A Extraction / Insertion.
9424   if (Subtarget->hasSSE4A())
9425     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9426       return V;
9427
9428   int NumV2Elements =
9429       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9430
9431   // For single-input shuffles, there are some nicer lowering tricks we can use.
9432   if (NumV2Elements == 0) {
9433     // Check for being able to broadcast a single element.
9434     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9435                                                           Mask, Subtarget, DAG))
9436       return Broadcast;
9437
9438     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9439     // Notably, this handles splat and partial-splat shuffles more efficiently.
9440     // However, it only makes sense if the pre-duplication shuffle simplifies
9441     // things significantly. Currently, this means we need to be able to
9442     // express the pre-duplication shuffle as an i16 shuffle.
9443     //
9444     // FIXME: We should check for other patterns which can be widened into an
9445     // i16 shuffle as well.
9446     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9447       for (int i = 0; i < 16; i += 2)
9448         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9449           return false;
9450
9451       return true;
9452     };
9453     auto tryToWidenViaDuplication = [&]() -> SDValue {
9454       if (!canWidenViaDuplication(Mask))
9455         return SDValue();
9456       SmallVector<int, 4> LoInputs;
9457       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9458                    [](int M) { return M >= 0 && M < 8; });
9459       std::sort(LoInputs.begin(), LoInputs.end());
9460       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9461                      LoInputs.end());
9462       SmallVector<int, 4> HiInputs;
9463       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9464                    [](int M) { return M >= 8; });
9465       std::sort(HiInputs.begin(), HiInputs.end());
9466       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9467                      HiInputs.end());
9468
9469       bool TargetLo = LoInputs.size() >= HiInputs.size();
9470       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9471       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9472
9473       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9474       SmallDenseMap<int, int, 8> LaneMap;
9475       for (int I : InPlaceInputs) {
9476         PreDupI16Shuffle[I/2] = I/2;
9477         LaneMap[I] = I;
9478       }
9479       int j = TargetLo ? 0 : 4, je = j + 4;
9480       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9481         // Check if j is already a shuffle of this input. This happens when
9482         // there are two adjacent bytes after we move the low one.
9483         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9484           // If we haven't yet mapped the input, search for a slot into which
9485           // we can map it.
9486           while (j < je && PreDupI16Shuffle[j] != -1)
9487             ++j;
9488
9489           if (j == je)
9490             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9491             return SDValue();
9492
9493           // Map this input with the i16 shuffle.
9494           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9495         }
9496
9497         // Update the lane map based on the mapping we ended up with.
9498         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9499       }
9500       V1 = DAG.getBitcast(
9501           MVT::v16i8,
9502           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9503                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9504
9505       // Unpack the bytes to form the i16s that will be shuffled into place.
9506       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9507                        MVT::v16i8, V1, V1);
9508
9509       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9510       for (int i = 0; i < 16; ++i)
9511         if (Mask[i] != -1) {
9512           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9513           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9514           if (PostDupI16Shuffle[i / 2] == -1)
9515             PostDupI16Shuffle[i / 2] = MappedMask;
9516           else
9517             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9518                    "Conflicting entrties in the original shuffle!");
9519         }
9520       return DAG.getBitcast(
9521           MVT::v16i8,
9522           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9523                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9524     };
9525     if (SDValue V = tryToWidenViaDuplication())
9526       return V;
9527   }
9528
9529   if (SDValue Masked =
9530           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9531     return Masked;
9532
9533   // Use dedicated unpack instructions for masks that match their pattern.
9534   if (SDValue V =
9535           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9536     return V;
9537
9538   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9539   // with PSHUFB. It is important to do this before we attempt to generate any
9540   // blends but after all of the single-input lowerings. If the single input
9541   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9542   // want to preserve that and we can DAG combine any longer sequences into
9543   // a PSHUFB in the end. But once we start blending from multiple inputs,
9544   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9545   // and there are *very* few patterns that would actually be faster than the
9546   // PSHUFB approach because of its ability to zero lanes.
9547   //
9548   // FIXME: The only exceptions to the above are blends which are exact
9549   // interleavings with direct instructions supporting them. We currently don't
9550   // handle those well here.
9551   if (Subtarget->hasSSSE3()) {
9552     bool V1InUse = false;
9553     bool V2InUse = false;
9554
9555     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9556                                                 DAG, V1InUse, V2InUse);
9557
9558     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9559     // do so. This avoids using them to handle blends-with-zero which is
9560     // important as a single pshufb is significantly faster for that.
9561     if (V1InUse && V2InUse) {
9562       if (Subtarget->hasSSE41())
9563         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9564                                                       Mask, Subtarget, DAG))
9565           return Blend;
9566
9567       // We can use an unpack to do the blending rather than an or in some
9568       // cases. Even though the or may be (very minorly) more efficient, we
9569       // preference this lowering because there are common cases where part of
9570       // the complexity of the shuffles goes away when we do the final blend as
9571       // an unpack.
9572       // FIXME: It might be worth trying to detect if the unpack-feeding
9573       // shuffles will both be pshufb, in which case we shouldn't bother with
9574       // this.
9575       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9576               DL, MVT::v16i8, V1, V2, Mask, DAG))
9577         return Unpack;
9578     }
9579
9580     return PSHUFB;
9581   }
9582
9583   // There are special ways we can lower some single-element blends.
9584   if (NumV2Elements == 1)
9585     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9586                                                          Mask, Subtarget, DAG))
9587       return V;
9588
9589   if (SDValue BitBlend =
9590           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9591     return BitBlend;
9592
9593   // Check whether a compaction lowering can be done. This handles shuffles
9594   // which take every Nth element for some even N. See the helper function for
9595   // details.
9596   //
9597   // We special case these as they can be particularly efficiently handled with
9598   // the PACKUSB instruction on x86 and they show up in common patterns of
9599   // rearranging bytes to truncate wide elements.
9600   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9601     // NumEvenDrops is the power of two stride of the elements. Another way of
9602     // thinking about it is that we need to drop the even elements this many
9603     // times to get the original input.
9604     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9605
9606     // First we need to zero all the dropped bytes.
9607     assert(NumEvenDrops <= 3 &&
9608            "No support for dropping even elements more than 3 times.");
9609     // We use the mask type to pick which bytes are preserved based on how many
9610     // elements are dropped.
9611     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9612     SDValue ByteClearMask = DAG.getBitcast(
9613         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9614     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9615     if (!IsSingleInput)
9616       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9617
9618     // Now pack things back together.
9619     V1 = DAG.getBitcast(MVT::v8i16, V1);
9620     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9621     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9622     for (int i = 1; i < NumEvenDrops; ++i) {
9623       Result = DAG.getBitcast(MVT::v8i16, Result);
9624       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9625     }
9626
9627     return Result;
9628   }
9629
9630   // Handle multi-input cases by blending single-input shuffles.
9631   if (NumV2Elements > 0)
9632     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9633                                                       Mask, DAG);
9634
9635   // The fallback path for single-input shuffles widens this into two v8i16
9636   // vectors with unpacks, shuffles those, and then pulls them back together
9637   // with a pack.
9638   SDValue V = V1;
9639
9640   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9641   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9642   for (int i = 0; i < 16; ++i)
9643     if (Mask[i] >= 0)
9644       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9645
9646   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9647
9648   SDValue VLoHalf, VHiHalf;
9649   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9650   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9651   // i16s.
9652   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9653                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9654       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9655                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9656     // Use a mask to drop the high bytes.
9657     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9658     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9659                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9660
9661     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9662     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9663
9664     // Squash the masks to point directly into VLoHalf.
9665     for (int &M : LoBlendMask)
9666       if (M >= 0)
9667         M /= 2;
9668     for (int &M : HiBlendMask)
9669       if (M >= 0)
9670         M /= 2;
9671   } else {
9672     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9673     // VHiHalf so that we can blend them as i16s.
9674     VLoHalf = DAG.getBitcast(
9675         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9676     VHiHalf = DAG.getBitcast(
9677         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9678   }
9679
9680   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9681   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9682
9683   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9684 }
9685
9686 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9687 ///
9688 /// This routine breaks down the specific type of 128-bit shuffle and
9689 /// dispatches to the lowering routines accordingly.
9690 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9691                                         MVT VT, const X86Subtarget *Subtarget,
9692                                         SelectionDAG &DAG) {
9693   switch (VT.SimpleTy) {
9694   case MVT::v2i64:
9695     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9696   case MVT::v2f64:
9697     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9698   case MVT::v4i32:
9699     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9700   case MVT::v4f32:
9701     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9702   case MVT::v8i16:
9703     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9704   case MVT::v16i8:
9705     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9706
9707   default:
9708     llvm_unreachable("Unimplemented!");
9709   }
9710 }
9711
9712 /// \brief Helper function to test whether a shuffle mask could be
9713 /// simplified by widening the elements being shuffled.
9714 ///
9715 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9716 /// leaves it in an unspecified state.
9717 ///
9718 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9719 /// shuffle masks. The latter have the special property of a '-2' representing
9720 /// a zero-ed lane of a vector.
9721 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9722                                     SmallVectorImpl<int> &WidenedMask) {
9723   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9724     // If both elements are undef, its trivial.
9725     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9726       WidenedMask.push_back(SM_SentinelUndef);
9727       continue;
9728     }
9729
9730     // Check for an undef mask and a mask value properly aligned to fit with
9731     // a pair of values. If we find such a case, use the non-undef mask's value.
9732     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9733       WidenedMask.push_back(Mask[i + 1] / 2);
9734       continue;
9735     }
9736     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9737       WidenedMask.push_back(Mask[i] / 2);
9738       continue;
9739     }
9740
9741     // When zeroing, we need to spread the zeroing across both lanes to widen.
9742     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9743       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9744           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9745         WidenedMask.push_back(SM_SentinelZero);
9746         continue;
9747       }
9748       return false;
9749     }
9750
9751     // Finally check if the two mask values are adjacent and aligned with
9752     // a pair.
9753     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9754       WidenedMask.push_back(Mask[i] / 2);
9755       continue;
9756     }
9757
9758     // Otherwise we can't safely widen the elements used in this shuffle.
9759     return false;
9760   }
9761   assert(WidenedMask.size() == Mask.size() / 2 &&
9762          "Incorrect size of mask after widening the elements!");
9763
9764   return true;
9765 }
9766
9767 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9768 ///
9769 /// This routine just extracts two subvectors, shuffles them independently, and
9770 /// then concatenates them back together. This should work effectively with all
9771 /// AVX vector shuffle types.
9772 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9773                                           SDValue V2, ArrayRef<int> Mask,
9774                                           SelectionDAG &DAG) {
9775   assert(VT.getSizeInBits() >= 256 &&
9776          "Only for 256-bit or wider vector shuffles!");
9777   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9778   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9779
9780   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9781   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9782
9783   int NumElements = VT.getVectorNumElements();
9784   int SplitNumElements = NumElements / 2;
9785   MVT ScalarVT = VT.getVectorElementType();
9786   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9787
9788   // Rather than splitting build-vectors, just build two narrower build
9789   // vectors. This helps shuffling with splats and zeros.
9790   auto SplitVector = [&](SDValue V) {
9791     while (V.getOpcode() == ISD::BITCAST)
9792       V = V->getOperand(0);
9793
9794     MVT OrigVT = V.getSimpleValueType();
9795     int OrigNumElements = OrigVT.getVectorNumElements();
9796     int OrigSplitNumElements = OrigNumElements / 2;
9797     MVT OrigScalarVT = OrigVT.getVectorElementType();
9798     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9799
9800     SDValue LoV, HiV;
9801
9802     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9803     if (!BV) {
9804       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9805                         DAG.getIntPtrConstant(0, DL));
9806       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9807                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9808     } else {
9809
9810       SmallVector<SDValue, 16> LoOps, HiOps;
9811       for (int i = 0; i < OrigSplitNumElements; ++i) {
9812         LoOps.push_back(BV->getOperand(i));
9813         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9814       }
9815       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9816       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9817     }
9818     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9819                           DAG.getBitcast(SplitVT, HiV));
9820   };
9821
9822   SDValue LoV1, HiV1, LoV2, HiV2;
9823   std::tie(LoV1, HiV1) = SplitVector(V1);
9824   std::tie(LoV2, HiV2) = SplitVector(V2);
9825
9826   // Now create two 4-way blends of these half-width vectors.
9827   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9828     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9829     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9830     for (int i = 0; i < SplitNumElements; ++i) {
9831       int M = HalfMask[i];
9832       if (M >= NumElements) {
9833         if (M >= NumElements + SplitNumElements)
9834           UseHiV2 = true;
9835         else
9836           UseLoV2 = true;
9837         V2BlendMask.push_back(M - NumElements);
9838         V1BlendMask.push_back(-1);
9839         BlendMask.push_back(SplitNumElements + i);
9840       } else if (M >= 0) {
9841         if (M >= SplitNumElements)
9842           UseHiV1 = true;
9843         else
9844           UseLoV1 = true;
9845         V2BlendMask.push_back(-1);
9846         V1BlendMask.push_back(M);
9847         BlendMask.push_back(i);
9848       } else {
9849         V2BlendMask.push_back(-1);
9850         V1BlendMask.push_back(-1);
9851         BlendMask.push_back(-1);
9852       }
9853     }
9854
9855     // Because the lowering happens after all combining takes place, we need to
9856     // manually combine these blend masks as much as possible so that we create
9857     // a minimal number of high-level vector shuffle nodes.
9858
9859     // First try just blending the halves of V1 or V2.
9860     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9861       return DAG.getUNDEF(SplitVT);
9862     if (!UseLoV2 && !UseHiV2)
9863       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9864     if (!UseLoV1 && !UseHiV1)
9865       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9866
9867     SDValue V1Blend, V2Blend;
9868     if (UseLoV1 && UseHiV1) {
9869       V1Blend =
9870         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9871     } else {
9872       // We only use half of V1 so map the usage down into the final blend mask.
9873       V1Blend = UseLoV1 ? LoV1 : HiV1;
9874       for (int i = 0; i < SplitNumElements; ++i)
9875         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9876           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9877     }
9878     if (UseLoV2 && UseHiV2) {
9879       V2Blend =
9880         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9881     } else {
9882       // We only use half of V2 so map the usage down into the final blend mask.
9883       V2Blend = UseLoV2 ? LoV2 : HiV2;
9884       for (int i = 0; i < SplitNumElements; ++i)
9885         if (BlendMask[i] >= SplitNumElements)
9886           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9887     }
9888     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9889   };
9890   SDValue Lo = HalfBlend(LoMask);
9891   SDValue Hi = HalfBlend(HiMask);
9892   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9893 }
9894
9895 /// \brief Either split a vector in halves or decompose the shuffles and the
9896 /// blend.
9897 ///
9898 /// This is provided as a good fallback for many lowerings of non-single-input
9899 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9900 /// between splitting the shuffle into 128-bit components and stitching those
9901 /// back together vs. extracting the single-input shuffles and blending those
9902 /// results.
9903 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9904                                                 SDValue V2, ArrayRef<int> Mask,
9905                                                 SelectionDAG &DAG) {
9906   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9907                                             "lower single-input shuffles as it "
9908                                             "could then recurse on itself.");
9909   int Size = Mask.size();
9910
9911   // If this can be modeled as a broadcast of two elements followed by a blend,
9912   // prefer that lowering. This is especially important because broadcasts can
9913   // often fold with memory operands.
9914   auto DoBothBroadcast = [&] {
9915     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9916     for (int M : Mask)
9917       if (M >= Size) {
9918         if (V2BroadcastIdx == -1)
9919           V2BroadcastIdx = M - Size;
9920         else if (M - Size != V2BroadcastIdx)
9921           return false;
9922       } else if (M >= 0) {
9923         if (V1BroadcastIdx == -1)
9924           V1BroadcastIdx = M;
9925         else if (M != V1BroadcastIdx)
9926           return false;
9927       }
9928     return true;
9929   };
9930   if (DoBothBroadcast())
9931     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9932                                                       DAG);
9933
9934   // If the inputs all stem from a single 128-bit lane of each input, then we
9935   // split them rather than blending because the split will decompose to
9936   // unusually few instructions.
9937   int LaneCount = VT.getSizeInBits() / 128;
9938   int LaneSize = Size / LaneCount;
9939   SmallBitVector LaneInputs[2];
9940   LaneInputs[0].resize(LaneCount, false);
9941   LaneInputs[1].resize(LaneCount, false);
9942   for (int i = 0; i < Size; ++i)
9943     if (Mask[i] >= 0)
9944       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9945   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9946     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9947
9948   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9949   // that the decomposed single-input shuffles don't end up here.
9950   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9951 }
9952
9953 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9954 /// a permutation and blend of those lanes.
9955 ///
9956 /// This essentially blends the out-of-lane inputs to each lane into the lane
9957 /// from a permuted copy of the vector. This lowering strategy results in four
9958 /// instructions in the worst case for a single-input cross lane shuffle which
9959 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9960 /// of. Special cases for each particular shuffle pattern should be handled
9961 /// prior to trying this lowering.
9962 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9963                                                        SDValue V1, SDValue V2,
9964                                                        ArrayRef<int> Mask,
9965                                                        SelectionDAG &DAG) {
9966   // FIXME: This should probably be generalized for 512-bit vectors as well.
9967   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
9968   int LaneSize = Mask.size() / 2;
9969
9970   // If there are only inputs from one 128-bit lane, splitting will in fact be
9971   // less expensive. The flags track whether the given lane contains an element
9972   // that crosses to another lane.
9973   bool LaneCrossing[2] = {false, false};
9974   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9975     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9976       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9977   if (!LaneCrossing[0] || !LaneCrossing[1])
9978     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9979
9980   if (isSingleInputShuffleMask(Mask)) {
9981     SmallVector<int, 32> FlippedBlendMask;
9982     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9983       FlippedBlendMask.push_back(
9984           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9985                                   ? Mask[i]
9986                                   : Mask[i] % LaneSize +
9987                                         (i / LaneSize) * LaneSize + Size));
9988
9989     // Flip the vector, and blend the results which should now be in-lane. The
9990     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9991     // 5 for the high source. The value 3 selects the high half of source 2 and
9992     // the value 2 selects the low half of source 2. We only use source 2 to
9993     // allow folding it into a memory operand.
9994     unsigned PERMMask = 3 | 2 << 4;
9995     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9996                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9997     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9998   }
9999
10000   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10001   // will be handled by the above logic and a blend of the results, much like
10002   // other patterns in AVX.
10003   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10004 }
10005
10006 /// \brief Handle lowering 2-lane 128-bit shuffles.
10007 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10008                                         SDValue V2, ArrayRef<int> Mask,
10009                                         const X86Subtarget *Subtarget,
10010                                         SelectionDAG &DAG) {
10011   // TODO: If minimizing size and one of the inputs is a zero vector and the
10012   // the zero vector has only one use, we could use a VPERM2X128 to save the
10013   // instruction bytes needed to explicitly generate the zero vector.
10014
10015   // Blends are faster and handle all the non-lane-crossing cases.
10016   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10017                                                 Subtarget, DAG))
10018     return Blend;
10019
10020   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10021   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10022
10023   // If either input operand is a zero vector, use VPERM2X128 because its mask
10024   // allows us to replace the zero input with an implicit zero.
10025   if (!IsV1Zero && !IsV2Zero) {
10026     // Check for patterns which can be matched with a single insert of a 128-bit
10027     // subvector.
10028     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10029     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10030       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10031                                    VT.getVectorNumElements() / 2);
10032       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10033                                 DAG.getIntPtrConstant(0, DL));
10034       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10035                                 OnlyUsesV1 ? V1 : V2,
10036                                 DAG.getIntPtrConstant(0, DL));
10037       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10038     }
10039   }
10040
10041   // Otherwise form a 128-bit permutation. After accounting for undefs,
10042   // convert the 64-bit shuffle mask selection values into 128-bit
10043   // selection bits by dividing the indexes by 2 and shifting into positions
10044   // defined by a vperm2*128 instruction's immediate control byte.
10045
10046   // The immediate permute control byte looks like this:
10047   //    [1:0] - select 128 bits from sources for low half of destination
10048   //    [2]   - ignore
10049   //    [3]   - zero low half of destination
10050   //    [5:4] - select 128 bits from sources for high half of destination
10051   //    [6]   - ignore
10052   //    [7]   - zero high half of destination
10053
10054   int MaskLO = Mask[0];
10055   if (MaskLO == SM_SentinelUndef)
10056     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10057
10058   int MaskHI = Mask[2];
10059   if (MaskHI == SM_SentinelUndef)
10060     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10061
10062   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10063
10064   // If either input is a zero vector, replace it with an undef input.
10065   // Shuffle mask values <  4 are selecting elements of V1.
10066   // Shuffle mask values >= 4 are selecting elements of V2.
10067   // Adjust each half of the permute mask by clearing the half that was
10068   // selecting the zero vector and setting the zero mask bit.
10069   if (IsV1Zero) {
10070     V1 = DAG.getUNDEF(VT);
10071     if (MaskLO < 4)
10072       PermMask = (PermMask & 0xf0) | 0x08;
10073     if (MaskHI < 4)
10074       PermMask = (PermMask & 0x0f) | 0x80;
10075   }
10076   if (IsV2Zero) {
10077     V2 = DAG.getUNDEF(VT);
10078     if (MaskLO >= 4)
10079       PermMask = (PermMask & 0xf0) | 0x08;
10080     if (MaskHI >= 4)
10081       PermMask = (PermMask & 0x0f) | 0x80;
10082   }
10083
10084   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10085                      DAG.getConstant(PermMask, DL, MVT::i8));
10086 }
10087
10088 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10089 /// shuffling each lane.
10090 ///
10091 /// This will only succeed when the result of fixing the 128-bit lanes results
10092 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10093 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10094 /// the lane crosses early and then use simpler shuffles within each lane.
10095 ///
10096 /// FIXME: It might be worthwhile at some point to support this without
10097 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10098 /// in x86 only floating point has interesting non-repeating shuffles, and even
10099 /// those are still *marginally* more expensive.
10100 static SDValue lowerVectorShuffleByMerging128BitLanes(
10101     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10102     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10103   assert(!isSingleInputShuffleMask(Mask) &&
10104          "This is only useful with multiple inputs.");
10105
10106   int Size = Mask.size();
10107   int LaneSize = 128 / VT.getScalarSizeInBits();
10108   int NumLanes = Size / LaneSize;
10109   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10110
10111   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10112   // check whether the in-128-bit lane shuffles share a repeating pattern.
10113   SmallVector<int, 4> Lanes;
10114   Lanes.resize(NumLanes, -1);
10115   SmallVector<int, 4> InLaneMask;
10116   InLaneMask.resize(LaneSize, -1);
10117   for (int i = 0; i < Size; ++i) {
10118     if (Mask[i] < 0)
10119       continue;
10120
10121     int j = i / LaneSize;
10122
10123     if (Lanes[j] < 0) {
10124       // First entry we've seen for this lane.
10125       Lanes[j] = Mask[i] / LaneSize;
10126     } else if (Lanes[j] != Mask[i] / LaneSize) {
10127       // This doesn't match the lane selected previously!
10128       return SDValue();
10129     }
10130
10131     // Check that within each lane we have a consistent shuffle mask.
10132     int k = i % LaneSize;
10133     if (InLaneMask[k] < 0) {
10134       InLaneMask[k] = Mask[i] % LaneSize;
10135     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10136       // This doesn't fit a repeating in-lane mask.
10137       return SDValue();
10138     }
10139   }
10140
10141   // First shuffle the lanes into place.
10142   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10143                                 VT.getSizeInBits() / 64);
10144   SmallVector<int, 8> LaneMask;
10145   LaneMask.resize(NumLanes * 2, -1);
10146   for (int i = 0; i < NumLanes; ++i)
10147     if (Lanes[i] >= 0) {
10148       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10149       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10150     }
10151
10152   V1 = DAG.getBitcast(LaneVT, V1);
10153   V2 = DAG.getBitcast(LaneVT, V2);
10154   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10155
10156   // Cast it back to the type we actually want.
10157   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10158
10159   // Now do a simple shuffle that isn't lane crossing.
10160   SmallVector<int, 8> NewMask;
10161   NewMask.resize(Size, -1);
10162   for (int i = 0; i < Size; ++i)
10163     if (Mask[i] >= 0)
10164       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10165   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10166          "Must not introduce lane crosses at this point!");
10167
10168   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10169 }
10170
10171 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10172 /// given mask.
10173 ///
10174 /// This returns true if the elements from a particular input are already in the
10175 /// slot required by the given mask and require no permutation.
10176 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10177   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10178   int Size = Mask.size();
10179   for (int i = 0; i < Size; ++i)
10180     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10181       return false;
10182
10183   return true;
10184 }
10185
10186 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10187                                             ArrayRef<int> Mask, SDValue V1,
10188                                             SDValue V2, SelectionDAG &DAG) {
10189
10190   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10191   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10192   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10193   int NumElts = VT.getVectorNumElements();
10194   bool ShufpdMask = true;
10195   bool CommutableMask = true;
10196   unsigned Immediate = 0;
10197   for (int i = 0; i < NumElts; ++i) {
10198     if (Mask[i] < 0)
10199       continue;
10200     int Val = (i & 6) + NumElts * (i & 1);
10201     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10202     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10203       ShufpdMask = false;
10204     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10205       CommutableMask = false;
10206     Immediate |= (Mask[i] % 2) << i;
10207   }
10208   if (ShufpdMask)
10209     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10210                        DAG.getConstant(Immediate, DL, MVT::i8));
10211   if (CommutableMask)
10212     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10213                        DAG.getConstant(Immediate, DL, MVT::i8));
10214   return SDValue();
10215 }
10216
10217 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10218 ///
10219 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10220 /// isn't available.
10221 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10222                                        const X86Subtarget *Subtarget,
10223                                        SelectionDAG &DAG) {
10224   SDLoc DL(Op);
10225   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10226   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10227   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10228   ArrayRef<int> Mask = SVOp->getMask();
10229   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10230
10231   SmallVector<int, 4> WidenedMask;
10232   if (canWidenShuffleElements(Mask, WidenedMask))
10233     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10234                                     DAG);
10235
10236   if (isSingleInputShuffleMask(Mask)) {
10237     // Check for being able to broadcast a single element.
10238     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10239                                                           Mask, Subtarget, DAG))
10240       return Broadcast;
10241
10242     // Use low duplicate instructions for masks that match their pattern.
10243     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10244       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10245
10246     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10247       // Non-half-crossing single input shuffles can be lowerid with an
10248       // interleaved permutation.
10249       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10250                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10251       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10252                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10253     }
10254
10255     // With AVX2 we have direct support for this permutation.
10256     if (Subtarget->hasAVX2())
10257       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10258                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10259
10260     // Otherwise, fall back.
10261     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10262                                                    DAG);
10263   }
10264
10265   // Use dedicated unpack instructions for masks that match their pattern.
10266   if (SDValue V =
10267           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10268     return V;
10269
10270   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10271                                                 Subtarget, DAG))
10272     return Blend;
10273
10274   // Check if the blend happens to exactly fit that of SHUFPD.
10275   if (SDValue Op =
10276       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10277     return Op;
10278
10279   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10280   // shuffle. However, if we have AVX2 and either inputs are already in place,
10281   // we will be able to shuffle even across lanes the other input in a single
10282   // instruction so skip this pattern.
10283   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10284                                  isShuffleMaskInputInPlace(1, Mask))))
10285     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10286             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10287       return Result;
10288
10289   // If we have AVX2 then we always want to lower with a blend because an v4 we
10290   // can fully permute the elements.
10291   if (Subtarget->hasAVX2())
10292     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10293                                                       Mask, DAG);
10294
10295   // Otherwise fall back on generic lowering.
10296   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10297 }
10298
10299 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10300 ///
10301 /// This routine is only called when we have AVX2 and thus a reasonable
10302 /// instruction set for v4i64 shuffling..
10303 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10304                                        const X86Subtarget *Subtarget,
10305                                        SelectionDAG &DAG) {
10306   SDLoc DL(Op);
10307   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10308   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10309   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10310   ArrayRef<int> Mask = SVOp->getMask();
10311   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10312   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10313
10314   SmallVector<int, 4> WidenedMask;
10315   if (canWidenShuffleElements(Mask, WidenedMask))
10316     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10317                                     DAG);
10318
10319   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10320                                                 Subtarget, DAG))
10321     return Blend;
10322
10323   // Check for being able to broadcast a single element.
10324   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10325                                                         Mask, Subtarget, DAG))
10326     return Broadcast;
10327
10328   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10329   // use lower latency instructions that will operate on both 128-bit lanes.
10330   SmallVector<int, 2> RepeatedMask;
10331   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10332     if (isSingleInputShuffleMask(Mask)) {
10333       int PSHUFDMask[] = {-1, -1, -1, -1};
10334       for (int i = 0; i < 2; ++i)
10335         if (RepeatedMask[i] >= 0) {
10336           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10337           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10338         }
10339       return DAG.getBitcast(
10340           MVT::v4i64,
10341           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10342                       DAG.getBitcast(MVT::v8i32, V1),
10343                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10344     }
10345   }
10346
10347   // AVX2 provides a direct instruction for permuting a single input across
10348   // lanes.
10349   if (isSingleInputShuffleMask(Mask))
10350     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10351                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10352
10353   // Try to use shift instructions.
10354   if (SDValue Shift =
10355           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10356     return Shift;
10357
10358   // Use dedicated unpack instructions for masks that match their pattern.
10359   if (SDValue V =
10360           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10361     return V;
10362
10363   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10364   // shuffle. However, if we have AVX2 and either inputs are already in place,
10365   // we will be able to shuffle even across lanes the other input in a single
10366   // instruction so skip this pattern.
10367   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10368                                  isShuffleMaskInputInPlace(1, Mask))))
10369     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10370             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10371       return Result;
10372
10373   // Otherwise fall back on generic blend lowering.
10374   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10375                                                     Mask, DAG);
10376 }
10377
10378 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10379 ///
10380 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10381 /// isn't available.
10382 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10383                                        const X86Subtarget *Subtarget,
10384                                        SelectionDAG &DAG) {
10385   SDLoc DL(Op);
10386   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10387   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10389   ArrayRef<int> Mask = SVOp->getMask();
10390   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10391
10392   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10393                                                 Subtarget, DAG))
10394     return Blend;
10395
10396   // Check for being able to broadcast a single element.
10397   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10398                                                         Mask, Subtarget, DAG))
10399     return Broadcast;
10400
10401   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10402   // options to efficiently lower the shuffle.
10403   SmallVector<int, 4> RepeatedMask;
10404   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10405     assert(RepeatedMask.size() == 4 &&
10406            "Repeated masks must be half the mask width!");
10407
10408     // Use even/odd duplicate instructions for masks that match their pattern.
10409     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10410       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10411     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10412       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10413
10414     if (isSingleInputShuffleMask(Mask))
10415       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10416                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10417
10418     // Use dedicated unpack instructions for masks that match their pattern.
10419     if (SDValue V =
10420             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10421       return V;
10422
10423     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10424     // have already handled any direct blends. We also need to squash the
10425     // repeated mask into a simulated v4f32 mask.
10426     for (int i = 0; i < 4; ++i)
10427       if (RepeatedMask[i] >= 8)
10428         RepeatedMask[i] -= 4;
10429     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10430   }
10431
10432   // If we have a single input shuffle with different shuffle patterns in the
10433   // two 128-bit lanes use the variable mask to VPERMILPS.
10434   if (isSingleInputShuffleMask(Mask)) {
10435     SDValue VPermMask[8];
10436     for (int i = 0; i < 8; ++i)
10437       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10438                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10439     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10440       return DAG.getNode(
10441           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10442           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10443
10444     if (Subtarget->hasAVX2())
10445       return DAG.getNode(
10446           X86ISD::VPERMV, DL, MVT::v8f32,
10447           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10448                                                  MVT::v8i32, VPermMask)),
10449           V1);
10450
10451     // Otherwise, fall back.
10452     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10453                                                    DAG);
10454   }
10455
10456   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10457   // shuffle.
10458   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10459           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10460     return Result;
10461
10462   // If we have AVX2 then we always want to lower with a blend because at v8 we
10463   // can fully permute the elements.
10464   if (Subtarget->hasAVX2())
10465     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10466                                                       Mask, DAG);
10467
10468   // Otherwise fall back on generic lowering.
10469   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10470 }
10471
10472 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10473 ///
10474 /// This routine is only called when we have AVX2 and thus a reasonable
10475 /// instruction set for v8i32 shuffling..
10476 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10477                                        const X86Subtarget *Subtarget,
10478                                        SelectionDAG &DAG) {
10479   SDLoc DL(Op);
10480   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10481   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10482   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10483   ArrayRef<int> Mask = SVOp->getMask();
10484   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10485   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10486
10487   // Whenever we can lower this as a zext, that instruction is strictly faster
10488   // than any alternative. It also allows us to fold memory operands into the
10489   // shuffle in many cases.
10490   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10491                                                          Mask, Subtarget, DAG))
10492     return ZExt;
10493
10494   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10495                                                 Subtarget, DAG))
10496     return Blend;
10497
10498   // Check for being able to broadcast a single element.
10499   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10500                                                         Mask, Subtarget, DAG))
10501     return Broadcast;
10502
10503   // If the shuffle mask is repeated in each 128-bit lane we can use more
10504   // efficient instructions that mirror the shuffles across the two 128-bit
10505   // lanes.
10506   SmallVector<int, 4> RepeatedMask;
10507   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10508     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10509     if (isSingleInputShuffleMask(Mask))
10510       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10511                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10512
10513     // Use dedicated unpack instructions for masks that match their pattern.
10514     if (SDValue V =
10515             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10516       return V;
10517   }
10518
10519   // Try to use shift instructions.
10520   if (SDValue Shift =
10521           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10522     return Shift;
10523
10524   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10525           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10526     return Rotate;
10527
10528   // If the shuffle patterns aren't repeated but it is a single input, directly
10529   // generate a cross-lane VPERMD instruction.
10530   if (isSingleInputShuffleMask(Mask)) {
10531     SDValue VPermMask[8];
10532     for (int i = 0; i < 8; ++i)
10533       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10534                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10535     return DAG.getNode(
10536         X86ISD::VPERMV, DL, MVT::v8i32,
10537         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10538   }
10539
10540   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10541   // shuffle.
10542   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10543           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10544     return Result;
10545
10546   // Otherwise fall back on generic blend lowering.
10547   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10548                                                     Mask, DAG);
10549 }
10550
10551 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10552 ///
10553 /// This routine is only called when we have AVX2 and thus a reasonable
10554 /// instruction set for v16i16 shuffling..
10555 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10556                                         const X86Subtarget *Subtarget,
10557                                         SelectionDAG &DAG) {
10558   SDLoc DL(Op);
10559   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10560   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10561   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10562   ArrayRef<int> Mask = SVOp->getMask();
10563   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10564   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10565
10566   // Whenever we can lower this as a zext, that instruction is strictly faster
10567   // than any alternative. It also allows us to fold memory operands into the
10568   // shuffle in many cases.
10569   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10570                                                          Mask, Subtarget, DAG))
10571     return ZExt;
10572
10573   // Check for being able to broadcast a single element.
10574   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10575                                                         Mask, Subtarget, DAG))
10576     return Broadcast;
10577
10578   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10579                                                 Subtarget, DAG))
10580     return Blend;
10581
10582   // Use dedicated unpack instructions for masks that match their pattern.
10583   if (SDValue V =
10584           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10585     return V;
10586
10587   // Try to use shift instructions.
10588   if (SDValue Shift =
10589           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10590     return Shift;
10591
10592   // Try to use byte rotation instructions.
10593   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10594           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10595     return Rotate;
10596
10597   if (isSingleInputShuffleMask(Mask)) {
10598     // There are no generalized cross-lane shuffle operations available on i16
10599     // element types.
10600     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10601       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10602                                                      Mask, DAG);
10603
10604     SmallVector<int, 8> RepeatedMask;
10605     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10606       // As this is a single-input shuffle, the repeated mask should be
10607       // a strictly valid v8i16 mask that we can pass through to the v8i16
10608       // lowering to handle even the v16 case.
10609       return lowerV8I16GeneralSingleInputVectorShuffle(
10610           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10611     }
10612
10613     SDValue PSHUFBMask[32];
10614     for (int i = 0; i < 16; ++i) {
10615       if (Mask[i] == -1) {
10616         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10617         continue;
10618       }
10619
10620       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10621       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10622       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10623       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10624     }
10625     return DAG.getBitcast(MVT::v16i16,
10626                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10627                                       DAG.getBitcast(MVT::v32i8, V1),
10628                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10629                                                   MVT::v32i8, PSHUFBMask)));
10630   }
10631
10632   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10633   // shuffle.
10634   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10635           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10636     return Result;
10637
10638   // Otherwise fall back on generic lowering.
10639   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10640 }
10641
10642 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10643 ///
10644 /// This routine is only called when we have AVX2 and thus a reasonable
10645 /// instruction set for v32i8 shuffling..
10646 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10647                                        const X86Subtarget *Subtarget,
10648                                        SelectionDAG &DAG) {
10649   SDLoc DL(Op);
10650   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10651   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10652   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10653   ArrayRef<int> Mask = SVOp->getMask();
10654   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10655   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10656
10657   // Whenever we can lower this as a zext, that instruction is strictly faster
10658   // than any alternative. It also allows us to fold memory operands into the
10659   // shuffle in many cases.
10660   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10661                                                          Mask, Subtarget, DAG))
10662     return ZExt;
10663
10664   // Check for being able to broadcast a single element.
10665   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10666                                                         Mask, Subtarget, DAG))
10667     return Broadcast;
10668
10669   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10670                                                 Subtarget, DAG))
10671     return Blend;
10672
10673   // Use dedicated unpack instructions for masks that match their pattern.
10674   if (SDValue V =
10675           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10676     return V;
10677
10678   // Try to use shift instructions.
10679   if (SDValue Shift =
10680           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10681     return Shift;
10682
10683   // Try to use byte rotation instructions.
10684   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10685           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10686     return Rotate;
10687
10688   if (isSingleInputShuffleMask(Mask)) {
10689     // There are no generalized cross-lane shuffle operations available on i8
10690     // element types.
10691     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10692       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10693                                                      Mask, DAG);
10694
10695     SDValue PSHUFBMask[32];
10696     for (int i = 0; i < 32; ++i)
10697       PSHUFBMask[i] =
10698           Mask[i] < 0
10699               ? DAG.getUNDEF(MVT::i8)
10700               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10701                                 MVT::i8);
10702
10703     return DAG.getNode(
10704         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10705         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10706   }
10707
10708   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10709   // shuffle.
10710   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10711           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10712     return Result;
10713
10714   // Otherwise fall back on generic lowering.
10715   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10716 }
10717
10718 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10719 ///
10720 /// This routine either breaks down the specific type of a 256-bit x86 vector
10721 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10722 /// together based on the available instructions.
10723 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10724                                         MVT VT, const X86Subtarget *Subtarget,
10725                                         SelectionDAG &DAG) {
10726   SDLoc DL(Op);
10727   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10728   ArrayRef<int> Mask = SVOp->getMask();
10729
10730   // If we have a single input to the zero element, insert that into V1 if we
10731   // can do so cheaply.
10732   int NumElts = VT.getVectorNumElements();
10733   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10734     return M >= NumElts;
10735   });
10736
10737   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10738     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10739                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10740       return Insertion;
10741
10742   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10743   // can check for those subtargets here and avoid much of the subtarget
10744   // querying in the per-vector-type lowering routines. With AVX1 we have
10745   // essentially *zero* ability to manipulate a 256-bit vector with integer
10746   // types. Since we'll use floating point types there eventually, just
10747   // immediately cast everything to a float and operate entirely in that domain.
10748   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10749     int ElementBits = VT.getScalarSizeInBits();
10750     if (ElementBits < 32)
10751       // No floating point type available, decompose into 128-bit vectors.
10752       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10753
10754     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10755                                 VT.getVectorNumElements());
10756     V1 = DAG.getBitcast(FpVT, V1);
10757     V2 = DAG.getBitcast(FpVT, V2);
10758     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10759   }
10760
10761   switch (VT.SimpleTy) {
10762   case MVT::v4f64:
10763     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10764   case MVT::v4i64:
10765     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10766   case MVT::v8f32:
10767     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10768   case MVT::v8i32:
10769     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10770   case MVT::v16i16:
10771     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10772   case MVT::v32i8:
10773     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10774
10775   default:
10776     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10777   }
10778 }
10779
10780 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10781 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10782                                         ArrayRef<int> Mask,
10783                                         SDValue V1, SDValue V2,
10784                                         SelectionDAG &DAG) {
10785   assert(VT.getScalarSizeInBits() == 64 &&
10786          "Unexpected element type size for 128bit shuffle.");
10787
10788   // To handle 256 bit vector requires VLX and most probably
10789   // function lowerV2X128VectorShuffle() is better solution.
10790   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
10791
10792   SmallVector<int, 4> WidenedMask;
10793   if (!canWidenShuffleElements(Mask, WidenedMask))
10794     return SDValue();
10795
10796   // Form a 128-bit permutation.
10797   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10798   // bits defined by a vshuf64x2 instruction's immediate control byte.
10799   unsigned PermMask = 0, Imm = 0;
10800   unsigned ControlBitsNum = WidenedMask.size() / 2;
10801
10802   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10803     if (WidenedMask[i] == SM_SentinelZero)
10804       return SDValue();
10805
10806     // Use first element in place of undef mask.
10807     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10808     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10809   }
10810
10811   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10812                      DAG.getConstant(PermMask, DL, MVT::i8));
10813 }
10814
10815 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10816                                            ArrayRef<int> Mask, SDValue V1,
10817                                            SDValue V2, SelectionDAG &DAG) {
10818
10819   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10820
10821   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10822   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10823
10824   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10825   if (isSingleInputShuffleMask(Mask))
10826     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10827
10828   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10829 }
10830
10831 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10832 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10833                                        const X86Subtarget *Subtarget,
10834                                        SelectionDAG &DAG) {
10835   SDLoc DL(Op);
10836   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10837   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10838   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10839   ArrayRef<int> Mask = SVOp->getMask();
10840   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10841
10842   if (SDValue Shuf128 =
10843           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10844     return Shuf128;
10845
10846   if (SDValue Unpck =
10847           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10848     return Unpck;
10849
10850   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10851 }
10852
10853 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10854 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10855                                         const X86Subtarget *Subtarget,
10856                                         SelectionDAG &DAG) {
10857   SDLoc DL(Op);
10858   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10859   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10860   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10861   ArrayRef<int> Mask = SVOp->getMask();
10862   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10863
10864   if (SDValue Unpck =
10865           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10866     return Unpck;
10867
10868   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10869 }
10870
10871 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10872 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10873                                        const X86Subtarget *Subtarget,
10874                                        SelectionDAG &DAG) {
10875   SDLoc DL(Op);
10876   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10877   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10878   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10879   ArrayRef<int> Mask = SVOp->getMask();
10880   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10881
10882   if (SDValue Shuf128 =
10883           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10884     return Shuf128;
10885
10886   if (SDValue Unpck =
10887           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10888     return Unpck;
10889
10890   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10891 }
10892
10893 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10894 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10895                                         const X86Subtarget *Subtarget,
10896                                         SelectionDAG &DAG) {
10897   SDLoc DL(Op);
10898   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10899   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10900   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10901   ArrayRef<int> Mask = SVOp->getMask();
10902   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10903
10904   if (SDValue Unpck =
10905           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10906     return Unpck;
10907
10908   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10909 }
10910
10911 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10912 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10913                                         const X86Subtarget *Subtarget,
10914                                         SelectionDAG &DAG) {
10915   SDLoc DL(Op);
10916   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10917   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10918   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10919   ArrayRef<int> Mask = SVOp->getMask();
10920   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10921   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10922
10923   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10924 }
10925
10926 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10927 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10928                                        const X86Subtarget *Subtarget,
10929                                        SelectionDAG &DAG) {
10930   SDLoc DL(Op);
10931   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10932   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10933   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10934   ArrayRef<int> Mask = SVOp->getMask();
10935   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10936   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10937
10938   // FIXME: Implement direct support for this type!
10939   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10940 }
10941
10942 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10943 ///
10944 /// This routine either breaks down the specific type of a 512-bit x86 vector
10945 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10946 /// together based on the available instructions.
10947 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10948                                         MVT VT, const X86Subtarget *Subtarget,
10949                                         SelectionDAG &DAG) {
10950   SDLoc DL(Op);
10951   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10952   ArrayRef<int> Mask = SVOp->getMask();
10953   assert(Subtarget->hasAVX512() &&
10954          "Cannot lower 512-bit vectors w/ basic ISA!");
10955
10956   // Check for being able to broadcast a single element.
10957   if (SDValue Broadcast =
10958           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10959     return Broadcast;
10960
10961   // Dispatch to each element type for lowering. If we don't have supprot for
10962   // specific element type shuffles at 512 bits, immediately split them and
10963   // lower them. Each lowering routine of a given type is allowed to assume that
10964   // the requisite ISA extensions for that element type are available.
10965   switch (VT.SimpleTy) {
10966   case MVT::v8f64:
10967     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10968   case MVT::v16f32:
10969     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10970   case MVT::v8i64:
10971     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10972   case MVT::v16i32:
10973     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10974   case MVT::v32i16:
10975     if (Subtarget->hasBWI())
10976       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10977     break;
10978   case MVT::v64i8:
10979     if (Subtarget->hasBWI())
10980       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10981     break;
10982
10983   default:
10984     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10985   }
10986
10987   // Otherwise fall back on splitting.
10988   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10989 }
10990
10991 // Lower vXi1 vector shuffles.
10992 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10993 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10994 // vector, shuffle and then truncate it back.
10995 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10996                                       MVT VT, const X86Subtarget *Subtarget,
10997                                       SelectionDAG &DAG) {
10998   SDLoc DL(Op);
10999   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11000   ArrayRef<int> Mask = SVOp->getMask();
11001   assert(Subtarget->hasAVX512() &&
11002          "Cannot lower 512-bit vectors w/o basic ISA!");
11003   MVT ExtVT;
11004   switch (VT.SimpleTy) {
11005   default:
11006     llvm_unreachable("Expected a vector of i1 elements");
11007   case MVT::v2i1:
11008     ExtVT = MVT::v2i64;
11009     break;
11010   case MVT::v4i1:
11011     ExtVT = MVT::v4i32;
11012     break;
11013   case MVT::v8i1:
11014     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11015     break;
11016   case MVT::v16i1:
11017     ExtVT = MVT::v16i32;
11018     break;
11019   case MVT::v32i1:
11020     ExtVT = MVT::v32i16;
11021     break;
11022   case MVT::v64i1:
11023     ExtVT = MVT::v64i8;
11024     break;
11025   }
11026
11027   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11028     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11029   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11030     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11031   else
11032     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11033
11034   if (V2.isUndef())
11035     V2 = DAG.getUNDEF(ExtVT);
11036   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11037     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11038   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11039     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11040   else
11041     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11042   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11043                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11044 }
11045 /// \brief Top-level lowering for x86 vector shuffles.
11046 ///
11047 /// This handles decomposition, canonicalization, and lowering of all x86
11048 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11049 /// above in helper routines. The canonicalization attempts to widen shuffles
11050 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11051 /// s.t. only one of the two inputs needs to be tested, etc.
11052 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11053                                   SelectionDAG &DAG) {
11054   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11055   ArrayRef<int> Mask = SVOp->getMask();
11056   SDValue V1 = Op.getOperand(0);
11057   SDValue V2 = Op.getOperand(1);
11058   MVT VT = Op.getSimpleValueType();
11059   int NumElements = VT.getVectorNumElements();
11060   SDLoc dl(Op);
11061   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11062
11063   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11064          "Can't lower MMX shuffles");
11065
11066   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11067   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11068   if (V1IsUndef && V2IsUndef)
11069     return DAG.getUNDEF(VT);
11070
11071   // When we create a shuffle node we put the UNDEF node to second operand,
11072   // but in some cases the first operand may be transformed to UNDEF.
11073   // In this case we should just commute the node.
11074   if (V1IsUndef)
11075     return DAG.getCommutedVectorShuffle(*SVOp);
11076
11077   // Check for non-undef masks pointing at an undef vector and make the masks
11078   // undef as well. This makes it easier to match the shuffle based solely on
11079   // the mask.
11080   if (V2IsUndef)
11081     for (int M : Mask)
11082       if (M >= NumElements) {
11083         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11084         for (int &M : NewMask)
11085           if (M >= NumElements)
11086             M = -1;
11087         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11088       }
11089
11090   // We actually see shuffles that are entirely re-arrangements of a set of
11091   // zero inputs. This mostly happens while decomposing complex shuffles into
11092   // simple ones. Directly lower these as a buildvector of zeros.
11093   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11094   if (Zeroable.all())
11095     return getZeroVector(VT, Subtarget, DAG, dl);
11096
11097   // Try to collapse shuffles into using a vector type with fewer elements but
11098   // wider element types. We cap this to not form integers or floating point
11099   // elements wider than 64 bits, but it might be interesting to form i128
11100   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11101   SmallVector<int, 16> WidenedMask;
11102   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11103       canWidenShuffleElements(Mask, WidenedMask)) {
11104     MVT NewEltVT = VT.isFloatingPoint()
11105                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11106                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11107     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11108     // Make sure that the new vector type is legal. For example, v2f64 isn't
11109     // legal on SSE1.
11110     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11111       V1 = DAG.getBitcast(NewVT, V1);
11112       V2 = DAG.getBitcast(NewVT, V2);
11113       return DAG.getBitcast(
11114           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11115     }
11116   }
11117
11118   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11119   for (int M : SVOp->getMask())
11120     if (M < 0)
11121       ++NumUndefElements;
11122     else if (M < NumElements)
11123       ++NumV1Elements;
11124     else
11125       ++NumV2Elements;
11126
11127   // Commute the shuffle as needed such that more elements come from V1 than
11128   // V2. This allows us to match the shuffle pattern strictly on how many
11129   // elements come from V1 without handling the symmetric cases.
11130   if (NumV2Elements > NumV1Elements)
11131     return DAG.getCommutedVectorShuffle(*SVOp);
11132
11133   // When the number of V1 and V2 elements are the same, try to minimize the
11134   // number of uses of V2 in the low half of the vector. When that is tied,
11135   // ensure that the sum of indices for V1 is equal to or lower than the sum
11136   // indices for V2. When those are equal, try to ensure that the number of odd
11137   // indices for V1 is lower than the number of odd indices for V2.
11138   if (NumV1Elements == NumV2Elements) {
11139     int LowV1Elements = 0, LowV2Elements = 0;
11140     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11141       if (M >= NumElements)
11142         ++LowV2Elements;
11143       else if (M >= 0)
11144         ++LowV1Elements;
11145     if (LowV2Elements > LowV1Elements) {
11146       return DAG.getCommutedVectorShuffle(*SVOp);
11147     } else if (LowV2Elements == LowV1Elements) {
11148       int SumV1Indices = 0, SumV2Indices = 0;
11149       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11150         if (SVOp->getMask()[i] >= NumElements)
11151           SumV2Indices += i;
11152         else if (SVOp->getMask()[i] >= 0)
11153           SumV1Indices += i;
11154       if (SumV2Indices < SumV1Indices) {
11155         return DAG.getCommutedVectorShuffle(*SVOp);
11156       } else if (SumV2Indices == SumV1Indices) {
11157         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11158         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11159           if (SVOp->getMask()[i] >= NumElements)
11160             NumV2OddIndices += i % 2;
11161           else if (SVOp->getMask()[i] >= 0)
11162             NumV1OddIndices += i % 2;
11163         if (NumV2OddIndices < NumV1OddIndices)
11164           return DAG.getCommutedVectorShuffle(*SVOp);
11165       }
11166     }
11167   }
11168
11169   // For each vector width, delegate to a specialized lowering routine.
11170   if (VT.is128BitVector())
11171     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11172
11173   if (VT.is256BitVector())
11174     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11175
11176   if (VT.is512BitVector())
11177     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11178
11179   if (Is1BitVector)
11180     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11181   llvm_unreachable("Unimplemented!");
11182 }
11183
11184 // This function assumes its argument is a BUILD_VECTOR of constants or
11185 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11186 // true.
11187 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11188                                     unsigned &MaskValue) {
11189   MaskValue = 0;
11190   unsigned NumElems = BuildVector->getNumOperands();
11191
11192   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11193   // We don't handle the >2 lanes case right now.
11194   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11195   if (NumLanes > 2)
11196     return false;
11197
11198   unsigned NumElemsInLane = NumElems / NumLanes;
11199
11200   // Blend for v16i16 should be symmetric for the both lanes.
11201   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11202     SDValue EltCond = BuildVector->getOperand(i);
11203     SDValue SndLaneEltCond =
11204         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11205
11206     int Lane1Cond = -1, Lane2Cond = -1;
11207     if (isa<ConstantSDNode>(EltCond))
11208       Lane1Cond = !isZero(EltCond);
11209     if (isa<ConstantSDNode>(SndLaneEltCond))
11210       Lane2Cond = !isZero(SndLaneEltCond);
11211
11212     unsigned LaneMask = 0;
11213     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11214       // Lane1Cond != 0, means we want the first argument.
11215       // Lane1Cond == 0, means we want the second argument.
11216       // The encoding of this argument is 0 for the first argument, 1
11217       // for the second. Therefore, invert the condition.
11218       LaneMask = !Lane1Cond << i;
11219     else if (Lane1Cond < 0)
11220       LaneMask = !Lane2Cond << i;
11221     else
11222       return false;
11223
11224     MaskValue |= LaneMask;
11225     if (NumLanes == 2)
11226       MaskValue |= LaneMask << NumElemsInLane;
11227   }
11228   return true;
11229 }
11230
11231 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11232 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11233                                            const X86Subtarget *Subtarget,
11234                                            SelectionDAG &DAG) {
11235   SDValue Cond = Op.getOperand(0);
11236   SDValue LHS = Op.getOperand(1);
11237   SDValue RHS = Op.getOperand(2);
11238   SDLoc dl(Op);
11239   MVT VT = Op.getSimpleValueType();
11240
11241   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11242     return SDValue();
11243   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11244
11245   // Only non-legal VSELECTs reach this lowering, convert those into generic
11246   // shuffles and re-use the shuffle lowering path for blends.
11247   SmallVector<int, 32> Mask;
11248   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11249     SDValue CondElt = CondBV->getOperand(i);
11250     Mask.push_back(
11251         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11252   }
11253   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11254 }
11255
11256 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11257   // A vselect where all conditions and data are constants can be optimized into
11258   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11259   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11260       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11261       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11262     return SDValue();
11263
11264   // Try to lower this to a blend-style vector shuffle. This can handle all
11265   // constant condition cases.
11266   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11267     return BlendOp;
11268
11269   // Variable blends are only legal from SSE4.1 onward.
11270   if (!Subtarget->hasSSE41())
11271     return SDValue();
11272
11273   // Only some types will be legal on some subtargets. If we can emit a legal
11274   // VSELECT-matching blend, return Op, and but if we need to expand, return
11275   // a null value.
11276   switch (Op.getSimpleValueType().SimpleTy) {
11277   default:
11278     // Most of the vector types have blends past SSE4.1.
11279     return Op;
11280
11281   case MVT::v32i8:
11282     // The byte blends for AVX vectors were introduced only in AVX2.
11283     if (Subtarget->hasAVX2())
11284       return Op;
11285
11286     return SDValue();
11287
11288   case MVT::v8i16:
11289   case MVT::v16i16:
11290     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11291     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11292       return Op;
11293
11294     // FIXME: We should custom lower this by fixing the condition and using i8
11295     // blends.
11296     return SDValue();
11297   }
11298 }
11299
11300 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11301   MVT VT = Op.getSimpleValueType();
11302   SDLoc dl(Op);
11303
11304   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11305     return SDValue();
11306
11307   if (VT.getSizeInBits() == 8) {
11308     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11309                                   Op.getOperand(0), Op.getOperand(1));
11310     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11311                                   DAG.getValueType(VT));
11312     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11313   }
11314
11315   if (VT.getSizeInBits() == 16) {
11316     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11317     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11318     if (Idx == 0)
11319       return DAG.getNode(
11320           ISD::TRUNCATE, dl, MVT::i16,
11321           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11322                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11323                       Op.getOperand(1)));
11324     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11325                                   Op.getOperand(0), Op.getOperand(1));
11326     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11327                                   DAG.getValueType(VT));
11328     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11329   }
11330
11331   if (VT == MVT::f32) {
11332     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11333     // the result back to FR32 register. It's only worth matching if the
11334     // result has a single use which is a store or a bitcast to i32.  And in
11335     // the case of a store, it's not worth it if the index is a constant 0,
11336     // because a MOVSSmr can be used instead, which is smaller and faster.
11337     if (!Op.hasOneUse())
11338       return SDValue();
11339     SDNode *User = *Op.getNode()->use_begin();
11340     if ((User->getOpcode() != ISD::STORE ||
11341          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11342           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11343         (User->getOpcode() != ISD::BITCAST ||
11344          User->getValueType(0) != MVT::i32))
11345       return SDValue();
11346     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11347                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11348                                   Op.getOperand(1));
11349     return DAG.getBitcast(MVT::f32, Extract);
11350   }
11351
11352   if (VT == MVT::i32 || VT == MVT::i64) {
11353     // ExtractPS/pextrq works with constant index.
11354     if (isa<ConstantSDNode>(Op.getOperand(1)))
11355       return Op;
11356   }
11357   return SDValue();
11358 }
11359
11360 /// Extract one bit from mask vector, like v16i1 or v8i1.
11361 /// AVX-512 feature.
11362 SDValue
11363 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11364   SDValue Vec = Op.getOperand(0);
11365   SDLoc dl(Vec);
11366   MVT VecVT = Vec.getSimpleValueType();
11367   SDValue Idx = Op.getOperand(1);
11368   MVT EltVT = Op.getSimpleValueType();
11369
11370   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11371   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11372          "Unexpected vector type in ExtractBitFromMaskVector");
11373
11374   // variable index can't be handled in mask registers,
11375   // extend vector to VR512
11376   if (!isa<ConstantSDNode>(Idx)) {
11377     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11378     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11379     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11380                               ExtVT.getVectorElementType(), Ext, Idx);
11381     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11382   }
11383
11384   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11385   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11386   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11387     rc = getRegClassFor(MVT::v16i1);
11388   unsigned MaxSift = rc->getSize()*8 - 1;
11389   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11390                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11391   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11392                     DAG.getConstant(MaxSift, dl, MVT::i8));
11393   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11394                        DAG.getIntPtrConstant(0, dl));
11395 }
11396
11397 SDValue
11398 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11399                                            SelectionDAG &DAG) const {
11400   SDLoc dl(Op);
11401   SDValue Vec = Op.getOperand(0);
11402   MVT VecVT = Vec.getSimpleValueType();
11403   SDValue Idx = Op.getOperand(1);
11404
11405   if (Op.getSimpleValueType() == MVT::i1)
11406     return ExtractBitFromMaskVector(Op, DAG);
11407
11408   if (!isa<ConstantSDNode>(Idx)) {
11409     if (VecVT.is512BitVector() ||
11410         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11411          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11412
11413       MVT MaskEltVT =
11414         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11415       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11416                                     MaskEltVT.getSizeInBits());
11417
11418       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11419       auto PtrVT = getPointerTy(DAG.getDataLayout());
11420       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11421                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11422                                  DAG.getConstant(0, dl, PtrVT));
11423       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11424       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11425                          DAG.getConstant(0, dl, PtrVT));
11426     }
11427     return SDValue();
11428   }
11429
11430   // If this is a 256-bit vector result, first extract the 128-bit vector and
11431   // then extract the element from the 128-bit vector.
11432   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11433
11434     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11435     // Get the 128-bit vector.
11436     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11437     MVT EltVT = VecVT.getVectorElementType();
11438
11439     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11440     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11441
11442     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11443     // this can be done with a mask.
11444     IdxVal &= ElemsPerChunk - 1;
11445     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11446                        DAG.getConstant(IdxVal, dl, MVT::i32));
11447   }
11448
11449   assert(VecVT.is128BitVector() && "Unexpected vector length");
11450
11451   if (Subtarget->hasSSE41())
11452     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11453       return Res;
11454
11455   MVT VT = Op.getSimpleValueType();
11456   // TODO: handle v16i8.
11457   if (VT.getSizeInBits() == 16) {
11458     SDValue Vec = Op.getOperand(0);
11459     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11460     if (Idx == 0)
11461       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11462                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11463                                      DAG.getBitcast(MVT::v4i32, Vec),
11464                                      Op.getOperand(1)));
11465     // Transform it so it match pextrw which produces a 32-bit result.
11466     MVT EltVT = MVT::i32;
11467     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11468                                   Op.getOperand(0), Op.getOperand(1));
11469     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11470                                   DAG.getValueType(VT));
11471     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11472   }
11473
11474   if (VT.getSizeInBits() == 32) {
11475     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11476     if (Idx == 0)
11477       return Op;
11478
11479     // SHUFPS the element to the lowest double word, then movss.
11480     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11481     MVT VVT = Op.getOperand(0).getSimpleValueType();
11482     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11483                                        DAG.getUNDEF(VVT), Mask);
11484     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11485                        DAG.getIntPtrConstant(0, dl));
11486   }
11487
11488   if (VT.getSizeInBits() == 64) {
11489     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11490     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11491     //        to match extract_elt for f64.
11492     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11493     if (Idx == 0)
11494       return Op;
11495
11496     // UNPCKHPD the element to the lowest double word, then movsd.
11497     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11498     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11499     int Mask[2] = { 1, -1 };
11500     MVT VVT = Op.getOperand(0).getSimpleValueType();
11501     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11502                                        DAG.getUNDEF(VVT), Mask);
11503     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11504                        DAG.getIntPtrConstant(0, dl));
11505   }
11506
11507   return SDValue();
11508 }
11509
11510 /// Insert one bit to mask vector, like v16i1 or v8i1.
11511 /// AVX-512 feature.
11512 SDValue
11513 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11514   SDLoc dl(Op);
11515   SDValue Vec = Op.getOperand(0);
11516   SDValue Elt = Op.getOperand(1);
11517   SDValue Idx = Op.getOperand(2);
11518   MVT VecVT = Vec.getSimpleValueType();
11519
11520   if (!isa<ConstantSDNode>(Idx)) {
11521     // Non constant index. Extend source and destination,
11522     // insert element and then truncate the result.
11523     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11524     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11525     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11526       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11527       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11528     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11529   }
11530
11531   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11532   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11533   if (IdxVal)
11534     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11535                            DAG.getConstant(IdxVal, dl, MVT::i8));
11536   if (Vec.getOpcode() == ISD::UNDEF)
11537     return EltInVec;
11538   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11539 }
11540
11541 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11542                                                   SelectionDAG &DAG) const {
11543   MVT VT = Op.getSimpleValueType();
11544   MVT EltVT = VT.getVectorElementType();
11545
11546   if (EltVT == MVT::i1)
11547     return InsertBitToMaskVector(Op, DAG);
11548
11549   SDLoc dl(Op);
11550   SDValue N0 = Op.getOperand(0);
11551   SDValue N1 = Op.getOperand(1);
11552   SDValue N2 = Op.getOperand(2);
11553   if (!isa<ConstantSDNode>(N2))
11554     return SDValue();
11555   auto *N2C = cast<ConstantSDNode>(N2);
11556   unsigned IdxVal = N2C->getZExtValue();
11557
11558   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11559   // into that, and then insert the subvector back into the result.
11560   if (VT.is256BitVector() || VT.is512BitVector()) {
11561     // With a 256-bit vector, we can insert into the zero element efficiently
11562     // using a blend if we have AVX or AVX2 and the right data type.
11563     if (VT.is256BitVector() && IdxVal == 0) {
11564       // TODO: It is worthwhile to cast integer to floating point and back
11565       // and incur a domain crossing penalty if that's what we'll end up
11566       // doing anyway after extracting to a 128-bit vector.
11567       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11568           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11569         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11570         N2 = DAG.getIntPtrConstant(1, dl);
11571         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11572       }
11573     }
11574
11575     // Get the desired 128-bit vector chunk.
11576     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11577
11578     // Insert the element into the desired chunk.
11579     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11580     assert(isPowerOf2_32(NumEltsIn128));
11581     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11582     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11583
11584     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11585                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11586
11587     // Insert the changed part back into the bigger vector
11588     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11589   }
11590   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11591
11592   if (Subtarget->hasSSE41()) {
11593     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11594       unsigned Opc;
11595       if (VT == MVT::v8i16) {
11596         Opc = X86ISD::PINSRW;
11597       } else {
11598         assert(VT == MVT::v16i8);
11599         Opc = X86ISD::PINSRB;
11600       }
11601
11602       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11603       // argument.
11604       if (N1.getValueType() != MVT::i32)
11605         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11606       if (N2.getValueType() != MVT::i32)
11607         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11608       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11609     }
11610
11611     if (EltVT == MVT::f32) {
11612       // Bits [7:6] of the constant are the source select. This will always be
11613       //   zero here. The DAG Combiner may combine an extract_elt index into
11614       //   these bits. For example (insert (extract, 3), 2) could be matched by
11615       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11616       // Bits [5:4] of the constant are the destination select. This is the
11617       //   value of the incoming immediate.
11618       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11619       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11620
11621       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11622       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11623         // If this is an insertion of 32-bits into the low 32-bits of
11624         // a vector, we prefer to generate a blend with immediate rather
11625         // than an insertps. Blends are simpler operations in hardware and so
11626         // will always have equal or better performance than insertps.
11627         // But if optimizing for size and there's a load folding opportunity,
11628         // generate insertps because blendps does not have a 32-bit memory
11629         // operand form.
11630         N2 = DAG.getIntPtrConstant(1, dl);
11631         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11632         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11633       }
11634       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11635       // Create this as a scalar to vector..
11636       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11637       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11638     }
11639
11640     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11641       // PINSR* works with constant index.
11642       return Op;
11643     }
11644   }
11645
11646   if (EltVT == MVT::i8)
11647     return SDValue();
11648
11649   if (EltVT.getSizeInBits() == 16) {
11650     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11651     // as its second argument.
11652     if (N1.getValueType() != MVT::i32)
11653       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11654     if (N2.getValueType() != MVT::i32)
11655       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11656     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11657   }
11658   return SDValue();
11659 }
11660
11661 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11662   SDLoc dl(Op);
11663   MVT OpVT = Op.getSimpleValueType();
11664
11665   // If this is a 256-bit vector result, first insert into a 128-bit
11666   // vector and then insert into the 256-bit vector.
11667   if (!OpVT.is128BitVector()) {
11668     // Insert into a 128-bit vector.
11669     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11670     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11671                                  OpVT.getVectorNumElements() / SizeFactor);
11672
11673     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11674
11675     // Insert the 128-bit vector.
11676     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11677   }
11678
11679   if (OpVT == MVT::v1i64 &&
11680       Op.getOperand(0).getValueType() == MVT::i64)
11681     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11682
11683   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11684   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11685   return DAG.getBitcast(
11686       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11687 }
11688
11689 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11690 // a simple subregister reference or explicit instructions to grab
11691 // upper bits of a vector.
11692 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11693                                       SelectionDAG &DAG) {
11694   SDLoc dl(Op);
11695   SDValue In =  Op.getOperand(0);
11696   SDValue Idx = Op.getOperand(1);
11697   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11698   MVT ResVT   = Op.getSimpleValueType();
11699   MVT InVT    = In.getSimpleValueType();
11700
11701   if (Subtarget->hasFp256()) {
11702     if (ResVT.is128BitVector() &&
11703         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11704         isa<ConstantSDNode>(Idx)) {
11705       return Extract128BitVector(In, IdxVal, DAG, dl);
11706     }
11707     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11708         isa<ConstantSDNode>(Idx)) {
11709       return Extract256BitVector(In, IdxVal, DAG, dl);
11710     }
11711   }
11712   return SDValue();
11713 }
11714
11715 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11716 // simple superregister reference or explicit instructions to insert
11717 // the upper bits of a vector.
11718 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11719                                      SelectionDAG &DAG) {
11720   if (!Subtarget->hasAVX())
11721     return SDValue();
11722
11723   SDLoc dl(Op);
11724   SDValue Vec = Op.getOperand(0);
11725   SDValue SubVec = Op.getOperand(1);
11726   SDValue Idx = Op.getOperand(2);
11727
11728   if (!isa<ConstantSDNode>(Idx))
11729     return SDValue();
11730
11731   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11732   MVT OpVT = Op.getSimpleValueType();
11733   MVT SubVecVT = SubVec.getSimpleValueType();
11734
11735   // Fold two 16-byte subvector loads into one 32-byte load:
11736   // (insert_subvector (insert_subvector undef, (load addr), 0),
11737   //                   (load addr + 16), Elts/2)
11738   // --> load32 addr
11739   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11740       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11741       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11742     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11743     if (Idx2 && Idx2->getZExtValue() == 0) {
11744       SDValue SubVec2 = Vec.getOperand(1);
11745       // If needed, look through a bitcast to get to the load.
11746       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11747         SubVec2 = SubVec2.getOperand(0);
11748
11749       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11750         bool Fast;
11751         unsigned Alignment = FirstLd->getAlignment();
11752         unsigned AS = FirstLd->getAddressSpace();
11753         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11754         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11755                                     OpVT, AS, Alignment, &Fast) && Fast) {
11756           SDValue Ops[] = { SubVec2, SubVec };
11757           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11758             return Ld;
11759         }
11760       }
11761     }
11762   }
11763
11764   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11765       SubVecVT.is128BitVector())
11766     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11767
11768   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11769     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11770
11771   if (OpVT.getVectorElementType() == MVT::i1) {
11772     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11773       return Op;
11774     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11775     SDValue Undef = DAG.getUNDEF(OpVT);
11776     unsigned NumElems = OpVT.getVectorNumElements();
11777     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11778
11779     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11780       // Zero upper bits of the Vec
11781       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11782       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11783
11784       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11785                                  SubVec, ZeroIdx);
11786       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11787       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11788     }
11789     if (IdxVal == 0) {
11790       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11791                                  SubVec, ZeroIdx);
11792       // Zero upper bits of the Vec2
11793       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11794       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11795       // Zero lower bits of the Vec
11796       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11797       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11798       // Merge them together
11799       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11800     }
11801   }
11802   return SDValue();
11803 }
11804
11805 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11806 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11807 // one of the above mentioned nodes. It has to be wrapped because otherwise
11808 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11809 // be used to form addressing mode. These wrapped nodes will be selected
11810 // into MOV32ri.
11811 SDValue
11812 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11813   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11814
11815   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11816   // global base reg.
11817   unsigned char OpFlag = 0;
11818   unsigned WrapperKind = X86ISD::Wrapper;
11819   CodeModel::Model M = DAG.getTarget().getCodeModel();
11820
11821   if (Subtarget->isPICStyleRIPRel() &&
11822       (M == CodeModel::Small || M == CodeModel::Kernel))
11823     WrapperKind = X86ISD::WrapperRIP;
11824   else if (Subtarget->isPICStyleGOT())
11825     OpFlag = X86II::MO_GOTOFF;
11826   else if (Subtarget->isPICStyleStubPIC())
11827     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11828
11829   auto PtrVT = getPointerTy(DAG.getDataLayout());
11830   SDValue Result = DAG.getTargetConstantPool(
11831       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11832   SDLoc DL(CP);
11833   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11834   // With PIC, the address is actually $g + Offset.
11835   if (OpFlag) {
11836     Result =
11837         DAG.getNode(ISD::ADD, DL, PtrVT,
11838                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11839   }
11840
11841   return Result;
11842 }
11843
11844 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11845   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11846
11847   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11848   // global base reg.
11849   unsigned char OpFlag = 0;
11850   unsigned WrapperKind = X86ISD::Wrapper;
11851   CodeModel::Model M = DAG.getTarget().getCodeModel();
11852
11853   if (Subtarget->isPICStyleRIPRel() &&
11854       (M == CodeModel::Small || M == CodeModel::Kernel))
11855     WrapperKind = X86ISD::WrapperRIP;
11856   else if (Subtarget->isPICStyleGOT())
11857     OpFlag = X86II::MO_GOTOFF;
11858   else if (Subtarget->isPICStyleStubPIC())
11859     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11860
11861   auto PtrVT = getPointerTy(DAG.getDataLayout());
11862   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11863   SDLoc DL(JT);
11864   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11865
11866   // With PIC, the address is actually $g + Offset.
11867   if (OpFlag)
11868     Result =
11869         DAG.getNode(ISD::ADD, DL, PtrVT,
11870                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11871
11872   return Result;
11873 }
11874
11875 SDValue
11876 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11877   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11878
11879   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11880   // global base reg.
11881   unsigned char OpFlag = 0;
11882   unsigned WrapperKind = X86ISD::Wrapper;
11883   CodeModel::Model M = DAG.getTarget().getCodeModel();
11884
11885   if (Subtarget->isPICStyleRIPRel() &&
11886       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11887     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11888       OpFlag = X86II::MO_GOTPCREL;
11889     WrapperKind = X86ISD::WrapperRIP;
11890   } else if (Subtarget->isPICStyleGOT()) {
11891     OpFlag = X86II::MO_GOT;
11892   } else if (Subtarget->isPICStyleStubPIC()) {
11893     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11894   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11895     OpFlag = X86II::MO_DARWIN_NONLAZY;
11896   }
11897
11898   auto PtrVT = getPointerTy(DAG.getDataLayout());
11899   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11900
11901   SDLoc DL(Op);
11902   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11903
11904   // With PIC, the address is actually $g + Offset.
11905   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11906       !Subtarget->is64Bit()) {
11907     Result =
11908         DAG.getNode(ISD::ADD, DL, PtrVT,
11909                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11910   }
11911
11912   // For symbols that require a load from a stub to get the address, emit the
11913   // load.
11914   if (isGlobalStubReference(OpFlag))
11915     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11916                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11917                          false, false, false, 0);
11918
11919   return Result;
11920 }
11921
11922 SDValue
11923 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11924   // Create the TargetBlockAddressAddress node.
11925   unsigned char OpFlags =
11926     Subtarget->ClassifyBlockAddressReference();
11927   CodeModel::Model M = DAG.getTarget().getCodeModel();
11928   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11929   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11930   SDLoc dl(Op);
11931   auto PtrVT = getPointerTy(DAG.getDataLayout());
11932   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11933
11934   if (Subtarget->isPICStyleRIPRel() &&
11935       (M == CodeModel::Small || M == CodeModel::Kernel))
11936     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11937   else
11938     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11939
11940   // With PIC, the address is actually $g + Offset.
11941   if (isGlobalRelativeToPICBase(OpFlags)) {
11942     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11943                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11944   }
11945
11946   return Result;
11947 }
11948
11949 SDValue
11950 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11951                                       int64_t Offset, SelectionDAG &DAG) const {
11952   // Create the TargetGlobalAddress node, folding in the constant
11953   // offset if it is legal.
11954   unsigned char OpFlags =
11955       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11956   CodeModel::Model M = DAG.getTarget().getCodeModel();
11957   auto PtrVT = getPointerTy(DAG.getDataLayout());
11958   SDValue Result;
11959   if (OpFlags == X86II::MO_NO_FLAG &&
11960       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11961     // A direct static reference to a global.
11962     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11963     Offset = 0;
11964   } else {
11965     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11966   }
11967
11968   if (Subtarget->isPICStyleRIPRel() &&
11969       (M == CodeModel::Small || M == CodeModel::Kernel))
11970     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11971   else
11972     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11973
11974   // With PIC, the address is actually $g + Offset.
11975   if (isGlobalRelativeToPICBase(OpFlags)) {
11976     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11977                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11978   }
11979
11980   // For globals that require a load from a stub to get the address, emit the
11981   // load.
11982   if (isGlobalStubReference(OpFlags))
11983     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11984                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11985                          false, false, false, 0);
11986
11987   // If there was a non-zero offset that we didn't fold, create an explicit
11988   // addition for it.
11989   if (Offset != 0)
11990     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11991                          DAG.getConstant(Offset, dl, PtrVT));
11992
11993   return Result;
11994 }
11995
11996 SDValue
11997 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11998   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11999   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12000   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12001 }
12002
12003 static SDValue
12004 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12005            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12006            unsigned char OperandFlags, bool LocalDynamic = false) {
12007   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12008   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12009   SDLoc dl(GA);
12010   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12011                                            GA->getValueType(0),
12012                                            GA->getOffset(),
12013                                            OperandFlags);
12014
12015   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12016                                            : X86ISD::TLSADDR;
12017
12018   if (InFlag) {
12019     SDValue Ops[] = { Chain,  TGA, *InFlag };
12020     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12021   } else {
12022     SDValue Ops[]  = { Chain, TGA };
12023     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12024   }
12025
12026   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12027   MFI->setAdjustsStack(true);
12028   MFI->setHasCalls(true);
12029
12030   SDValue Flag = Chain.getValue(1);
12031   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12032 }
12033
12034 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12035 static SDValue
12036 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12037                                 const EVT PtrVT) {
12038   SDValue InFlag;
12039   SDLoc dl(GA);  // ? function entry point might be better
12040   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12041                                    DAG.getNode(X86ISD::GlobalBaseReg,
12042                                                SDLoc(), PtrVT), InFlag);
12043   InFlag = Chain.getValue(1);
12044
12045   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12046 }
12047
12048 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12049 static SDValue
12050 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12051                                 const EVT PtrVT) {
12052   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12053                     X86::RAX, X86II::MO_TLSGD);
12054 }
12055
12056 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12057                                            SelectionDAG &DAG,
12058                                            const EVT PtrVT,
12059                                            bool is64Bit) {
12060   SDLoc dl(GA);
12061
12062   // Get the start address of the TLS block for this module.
12063   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12064       .getInfo<X86MachineFunctionInfo>();
12065   MFI->incNumLocalDynamicTLSAccesses();
12066
12067   SDValue Base;
12068   if (is64Bit) {
12069     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12070                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12071   } else {
12072     SDValue InFlag;
12073     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12074         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12075     InFlag = Chain.getValue(1);
12076     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12077                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12078   }
12079
12080   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12081   // of Base.
12082
12083   // Build x@dtpoff.
12084   unsigned char OperandFlags = X86II::MO_DTPOFF;
12085   unsigned WrapperKind = X86ISD::Wrapper;
12086   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12087                                            GA->getValueType(0),
12088                                            GA->getOffset(), OperandFlags);
12089   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12090
12091   // Add x@dtpoff with the base.
12092   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12093 }
12094
12095 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12096 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12097                                    const EVT PtrVT, TLSModel::Model model,
12098                                    bool is64Bit, bool isPIC) {
12099   SDLoc dl(GA);
12100
12101   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12102   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12103                                                          is64Bit ? 257 : 256));
12104
12105   SDValue ThreadPointer =
12106       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12107                   MachinePointerInfo(Ptr), false, false, false, 0);
12108
12109   unsigned char OperandFlags = 0;
12110   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12111   // initialexec.
12112   unsigned WrapperKind = X86ISD::Wrapper;
12113   if (model == TLSModel::LocalExec) {
12114     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12115   } else if (model == TLSModel::InitialExec) {
12116     if (is64Bit) {
12117       OperandFlags = X86II::MO_GOTTPOFF;
12118       WrapperKind = X86ISD::WrapperRIP;
12119     } else {
12120       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12121     }
12122   } else {
12123     llvm_unreachable("Unexpected model");
12124   }
12125
12126   // emit "addl x@ntpoff,%eax" (local exec)
12127   // or "addl x@indntpoff,%eax" (initial exec)
12128   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12129   SDValue TGA =
12130       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12131                                  GA->getOffset(), OperandFlags);
12132   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12133
12134   if (model == TLSModel::InitialExec) {
12135     if (isPIC && !is64Bit) {
12136       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12137                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12138                            Offset);
12139     }
12140
12141     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12142                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12143                          false, false, false, 0);
12144   }
12145
12146   // The address of the thread local variable is the add of the thread
12147   // pointer with the offset of the variable.
12148   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12149 }
12150
12151 SDValue
12152 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12153
12154   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12155   const GlobalValue *GV = GA->getGlobal();
12156   auto PtrVT = getPointerTy(DAG.getDataLayout());
12157
12158   if (Subtarget->isTargetELF()) {
12159     if (DAG.getTarget().Options.EmulatedTLS)
12160       return LowerToTLSEmulatedModel(GA, DAG);
12161     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12162     switch (model) {
12163       case TLSModel::GeneralDynamic:
12164         if (Subtarget->is64Bit())
12165           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12166         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12167       case TLSModel::LocalDynamic:
12168         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12169                                            Subtarget->is64Bit());
12170       case TLSModel::InitialExec:
12171       case TLSModel::LocalExec:
12172         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12173                                    DAG.getTarget().getRelocationModel() ==
12174                                        Reloc::PIC_);
12175     }
12176     llvm_unreachable("Unknown TLS model.");
12177   }
12178
12179   if (Subtarget->isTargetDarwin()) {
12180     // Darwin only has one model of TLS.  Lower to that.
12181     unsigned char OpFlag = 0;
12182     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12183                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12184
12185     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12186     // global base reg.
12187     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12188                  !Subtarget->is64Bit();
12189     if (PIC32)
12190       OpFlag = X86II::MO_TLVP_PIC_BASE;
12191     else
12192       OpFlag = X86II::MO_TLVP;
12193     SDLoc DL(Op);
12194     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12195                                                 GA->getValueType(0),
12196                                                 GA->getOffset(), OpFlag);
12197     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12198
12199     // With PIC32, the address is actually $g + Offset.
12200     if (PIC32)
12201       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12202                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12203                            Offset);
12204
12205     // Lowering the machine isd will make sure everything is in the right
12206     // location.
12207     SDValue Chain = DAG.getEntryNode();
12208     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12209     SDValue Args[] = { Chain, Offset };
12210     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12211
12212     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12213     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12214     MFI->setAdjustsStack(true);
12215
12216     // And our return value (tls address) is in the standard call return value
12217     // location.
12218     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12219     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12220   }
12221
12222   if (Subtarget->isTargetKnownWindowsMSVC() ||
12223       Subtarget->isTargetWindowsGNU()) {
12224     // Just use the implicit TLS architecture
12225     // Need to generate someting similar to:
12226     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12227     //                                  ; from TEB
12228     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12229     //   mov     rcx, qword [rdx+rcx*8]
12230     //   mov     eax, .tls$:tlsvar
12231     //   [rax+rcx] contains the address
12232     // Windows 64bit: gs:0x58
12233     // Windows 32bit: fs:__tls_array
12234
12235     SDLoc dl(GA);
12236     SDValue Chain = DAG.getEntryNode();
12237
12238     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12239     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12240     // use its literal value of 0x2C.
12241     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12242                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12243                                                              256)
12244                                         : Type::getInt32PtrTy(*DAG.getContext(),
12245                                                               257));
12246
12247     SDValue TlsArray = Subtarget->is64Bit()
12248                            ? DAG.getIntPtrConstant(0x58, dl)
12249                            : (Subtarget->isTargetWindowsGNU()
12250                                   ? DAG.getIntPtrConstant(0x2C, dl)
12251                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12252
12253     SDValue ThreadPointer =
12254         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12255                     false, false, 0);
12256
12257     SDValue res;
12258     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12259       res = ThreadPointer;
12260     } else {
12261       // Load the _tls_index variable
12262       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12263       if (Subtarget->is64Bit())
12264         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12265                              MachinePointerInfo(), MVT::i32, false, false,
12266                              false, 0);
12267       else
12268         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12269                           false, false, 0);
12270
12271       auto &DL = DAG.getDataLayout();
12272       SDValue Scale =
12273           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12274       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12275
12276       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12277     }
12278
12279     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12280                       false, 0);
12281
12282     // Get the offset of start of .tls section
12283     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12284                                              GA->getValueType(0),
12285                                              GA->getOffset(), X86II::MO_SECREL);
12286     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12287
12288     // The address of the thread local variable is the add of the thread
12289     // pointer with the offset of the variable.
12290     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12291   }
12292
12293   llvm_unreachable("TLS not implemented for this target.");
12294 }
12295
12296 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12297 /// and take a 2 x i32 value to shift plus a shift amount.
12298 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12299   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12300   MVT VT = Op.getSimpleValueType();
12301   unsigned VTBits = VT.getSizeInBits();
12302   SDLoc dl(Op);
12303   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12304   SDValue ShOpLo = Op.getOperand(0);
12305   SDValue ShOpHi = Op.getOperand(1);
12306   SDValue ShAmt  = Op.getOperand(2);
12307   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12308   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12309   // during isel.
12310   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12311                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12312   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12313                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12314                        : DAG.getConstant(0, dl, VT);
12315
12316   SDValue Tmp2, Tmp3;
12317   if (Op.getOpcode() == ISD::SHL_PARTS) {
12318     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12319     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12320   } else {
12321     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12322     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12323   }
12324
12325   // If the shift amount is larger or equal than the width of a part we can't
12326   // rely on the results of shld/shrd. Insert a test and select the appropriate
12327   // values for large shift amounts.
12328   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12329                                 DAG.getConstant(VTBits, dl, MVT::i8));
12330   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12331                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12332
12333   SDValue Hi, Lo;
12334   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12335   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12336   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12337
12338   if (Op.getOpcode() == ISD::SHL_PARTS) {
12339     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12340     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12341   } else {
12342     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12343     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12344   }
12345
12346   SDValue Ops[2] = { Lo, Hi };
12347   return DAG.getMergeValues(Ops, dl);
12348 }
12349
12350 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12351                                            SelectionDAG &DAG) const {
12352   SDValue Src = Op.getOperand(0);
12353   MVT SrcVT = Src.getSimpleValueType();
12354   MVT VT = Op.getSimpleValueType();
12355   SDLoc dl(Op);
12356
12357   if (SrcVT.isVector()) {
12358     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12359       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12360                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12361                          DAG.getUNDEF(SrcVT)));
12362     }
12363     if (SrcVT.getVectorElementType() == MVT::i1) {
12364       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12365       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12366                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12367     }
12368     return SDValue();
12369   }
12370
12371   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12372          "Unknown SINT_TO_FP to lower!");
12373
12374   // These are really Legal; return the operand so the caller accepts it as
12375   // Legal.
12376   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12377     return Op;
12378   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12379       Subtarget->is64Bit()) {
12380     return Op;
12381   }
12382
12383   unsigned Size = SrcVT.getSizeInBits()/8;
12384   MachineFunction &MF = DAG.getMachineFunction();
12385   auto PtrVT = getPointerTy(MF.getDataLayout());
12386   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12387   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12388   SDValue Chain = DAG.getStore(
12389       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12390       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12391       false, 0);
12392   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12393 }
12394
12395 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12396                                      SDValue StackSlot,
12397                                      SelectionDAG &DAG) const {
12398   // Build the FILD
12399   SDLoc DL(Op);
12400   SDVTList Tys;
12401   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12402   if (useSSE)
12403     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12404   else
12405     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12406
12407   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12408
12409   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12410   MachineMemOperand *MMO;
12411   if (FI) {
12412     int SSFI = FI->getIndex();
12413     MMO = DAG.getMachineFunction().getMachineMemOperand(
12414         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12415         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12416   } else {
12417     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12418     StackSlot = StackSlot.getOperand(1);
12419   }
12420   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12421   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12422                                            X86ISD::FILD, DL,
12423                                            Tys, Ops, SrcVT, MMO);
12424
12425   if (useSSE) {
12426     Chain = Result.getValue(1);
12427     SDValue InFlag = Result.getValue(2);
12428
12429     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12430     // shouldn't be necessary except that RFP cannot be live across
12431     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12432     MachineFunction &MF = DAG.getMachineFunction();
12433     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12434     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12435     auto PtrVT = getPointerTy(MF.getDataLayout());
12436     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12437     Tys = DAG.getVTList(MVT::Other);
12438     SDValue Ops[] = {
12439       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12440     };
12441     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12442         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12443         MachineMemOperand::MOStore, SSFISize, SSFISize);
12444
12445     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12446                                     Ops, Op.getValueType(), MMO);
12447     Result = DAG.getLoad(
12448         Op.getValueType(), DL, Chain, StackSlot,
12449         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12450         false, false, false, 0);
12451   }
12452
12453   return Result;
12454 }
12455
12456 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12457 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12458                                                SelectionDAG &DAG) const {
12459   // This algorithm is not obvious. Here it is what we're trying to output:
12460   /*
12461      movq       %rax,  %xmm0
12462      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12463      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12464      #ifdef __SSE3__
12465        haddpd   %xmm0, %xmm0
12466      #else
12467        pshufd   $0x4e, %xmm0, %xmm1
12468        addpd    %xmm1, %xmm0
12469      #endif
12470   */
12471
12472   SDLoc dl(Op);
12473   LLVMContext *Context = DAG.getContext();
12474
12475   // Build some magic constants.
12476   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12477   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12478   auto PtrVT = getPointerTy(DAG.getDataLayout());
12479   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12480
12481   SmallVector<Constant*,2> CV1;
12482   CV1.push_back(
12483     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12484                                       APInt(64, 0x4330000000000000ULL))));
12485   CV1.push_back(
12486     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12487                                       APInt(64, 0x4530000000000000ULL))));
12488   Constant *C1 = ConstantVector::get(CV1);
12489   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12490
12491   // Load the 64-bit value into an XMM register.
12492   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12493                             Op.getOperand(0));
12494   SDValue CLod0 =
12495       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12496                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12497                   false, false, false, 16);
12498   SDValue Unpck1 =
12499       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12500
12501   SDValue CLod1 =
12502       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12503                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12504                   false, false, false, 16);
12505   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12506   // TODO: Are there any fast-math-flags to propagate here?
12507   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12508   SDValue Result;
12509
12510   if (Subtarget->hasSSE3()) {
12511     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12512     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12513   } else {
12514     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12515     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12516                                            S2F, 0x4E, DAG);
12517     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12518                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12519   }
12520
12521   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12522                      DAG.getIntPtrConstant(0, dl));
12523 }
12524
12525 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12526 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12527                                                SelectionDAG &DAG) const {
12528   SDLoc dl(Op);
12529   // FP constant to bias correct the final result.
12530   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12531                                    MVT::f64);
12532
12533   // Load the 32-bit value into an XMM register.
12534   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12535                              Op.getOperand(0));
12536
12537   // Zero out the upper parts of the register.
12538   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12539
12540   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12541                      DAG.getBitcast(MVT::v2f64, Load),
12542                      DAG.getIntPtrConstant(0, dl));
12543
12544   // Or the load with the bias.
12545   SDValue Or = DAG.getNode(
12546       ISD::OR, dl, MVT::v2i64,
12547       DAG.getBitcast(MVT::v2i64,
12548                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12549       DAG.getBitcast(MVT::v2i64,
12550                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12551   Or =
12552       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12553                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12554
12555   // Subtract the bias.
12556   // TODO: Are there any fast-math-flags to propagate here?
12557   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12558
12559   // Handle final rounding.
12560   MVT DestVT = Op.getSimpleValueType();
12561
12562   if (DestVT.bitsLT(MVT::f64))
12563     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12564                        DAG.getIntPtrConstant(0, dl));
12565   if (DestVT.bitsGT(MVT::f64))
12566     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12567
12568   // Handle final rounding.
12569   return Sub;
12570 }
12571
12572 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12573                                      const X86Subtarget &Subtarget) {
12574   // The algorithm is the following:
12575   // #ifdef __SSE4_1__
12576   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12577   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12578   //                                 (uint4) 0x53000000, 0xaa);
12579   // #else
12580   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12581   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12582   // #endif
12583   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12584   //     return (float4) lo + fhi;
12585
12586   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12587   // reassociate the two FADDs, and if we do that, the algorithm fails
12588   // spectacularly (PR24512).
12589   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12590   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12591   // there's also the MachineCombiner reassociations happening on Machine IR.
12592   if (DAG.getTarget().Options.UnsafeFPMath)
12593     return SDValue();
12594
12595   SDLoc DL(Op);
12596   SDValue V = Op->getOperand(0);
12597   MVT VecIntVT = V.getSimpleValueType();
12598   bool Is128 = VecIntVT == MVT::v4i32;
12599   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12600   // If we convert to something else than the supported type, e.g., to v4f64,
12601   // abort early.
12602   if (VecFloatVT != Op->getSimpleValueType(0))
12603     return SDValue();
12604
12605   unsigned NumElts = VecIntVT.getVectorNumElements();
12606   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12607          "Unsupported custom type");
12608   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12609
12610   // In the #idef/#else code, we have in common:
12611   // - The vector of constants:
12612   // -- 0x4b000000
12613   // -- 0x53000000
12614   // - A shift:
12615   // -- v >> 16
12616
12617   // Create the splat vector for 0x4b000000.
12618   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12619   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12620                            CstLow, CstLow, CstLow, CstLow};
12621   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12622                                   makeArrayRef(&CstLowArray[0], NumElts));
12623   // Create the splat vector for 0x53000000.
12624   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12625   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12626                             CstHigh, CstHigh, CstHigh, CstHigh};
12627   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12628                                    makeArrayRef(&CstHighArray[0], NumElts));
12629
12630   // Create the right shift.
12631   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12632   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12633                              CstShift, CstShift, CstShift, CstShift};
12634   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12635                                     makeArrayRef(&CstShiftArray[0], NumElts));
12636   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12637
12638   SDValue Low, High;
12639   if (Subtarget.hasSSE41()) {
12640     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12641     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12642     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12643     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12644     // Low will be bitcasted right away, so do not bother bitcasting back to its
12645     // original type.
12646     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12647                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12648     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12649     //                                 (uint4) 0x53000000, 0xaa);
12650     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12651     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12652     // High will be bitcasted right away, so do not bother bitcasting back to
12653     // its original type.
12654     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12655                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12656   } else {
12657     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12658     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12659                                      CstMask, CstMask, CstMask);
12660     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12661     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12662     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12663
12664     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12665     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12666   }
12667
12668   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12669   SDValue CstFAdd = DAG.getConstantFP(
12670       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12671   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12672                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12673   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12674                                    makeArrayRef(&CstFAddArray[0], NumElts));
12675
12676   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12677   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12678   // TODO: Are there any fast-math-flags to propagate here?
12679   SDValue FHigh =
12680       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12681   //     return (float4) lo + fhi;
12682   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12683   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12684 }
12685
12686 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12687                                                SelectionDAG &DAG) const {
12688   SDValue N0 = Op.getOperand(0);
12689   MVT SVT = N0.getSimpleValueType();
12690   SDLoc dl(Op);
12691
12692   switch (SVT.SimpleTy) {
12693   default:
12694     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12695   case MVT::v4i8:
12696   case MVT::v4i16:
12697   case MVT::v8i8:
12698   case MVT::v8i16: {
12699     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12700     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12701                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12702   }
12703   case MVT::v4i32:
12704   case MVT::v8i32:
12705     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12706   case MVT::v16i8:
12707   case MVT::v16i16:
12708     assert(Subtarget->hasAVX512());
12709     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12710                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12711   }
12712 }
12713
12714 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12715                                            SelectionDAG &DAG) const {
12716   SDValue N0 = Op.getOperand(0);
12717   SDLoc dl(Op);
12718   auto PtrVT = getPointerTy(DAG.getDataLayout());
12719
12720   if (Op.getSimpleValueType().isVector())
12721     return lowerUINT_TO_FP_vec(Op, DAG);
12722
12723   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12724   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12725   // the optimization here.
12726   if (DAG.SignBitIsZero(N0))
12727     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12728
12729   MVT SrcVT = N0.getSimpleValueType();
12730   MVT DstVT = Op.getSimpleValueType();
12731
12732   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12733       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12734     // Conversions from unsigned i32 to f32/f64 are legal,
12735     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12736     return Op;
12737   }
12738
12739   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12740     return LowerUINT_TO_FP_i64(Op, DAG);
12741   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12742     return LowerUINT_TO_FP_i32(Op, DAG);
12743   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12744     return SDValue();
12745
12746   // Make a 64-bit buffer, and use it to build an FILD.
12747   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12748   if (SrcVT == MVT::i32) {
12749     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12750     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12751     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12752                                   StackSlot, MachinePointerInfo(),
12753                                   false, false, 0);
12754     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12755                                   OffsetSlot, MachinePointerInfo(),
12756                                   false, false, 0);
12757     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12758     return Fild;
12759   }
12760
12761   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12762   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12763                                StackSlot, MachinePointerInfo(),
12764                                false, false, 0);
12765   // For i64 source, we need to add the appropriate power of 2 if the input
12766   // was negative.  This is the same as the optimization in
12767   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12768   // we must be careful to do the computation in x87 extended precision, not
12769   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12770   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12771   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12772       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12773       MachineMemOperand::MOLoad, 8, 8);
12774
12775   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12776   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12777   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12778                                          MVT::i64, MMO);
12779
12780   APInt FF(32, 0x5F800000ULL);
12781
12782   // Check whether the sign bit is set.
12783   SDValue SignSet = DAG.getSetCC(
12784       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12785       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12786
12787   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12788   SDValue FudgePtr = DAG.getConstantPool(
12789       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12790
12791   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12792   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12793   SDValue Four = DAG.getIntPtrConstant(4, dl);
12794   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12795                                Zero, Four);
12796   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12797
12798   // Load the value out, extending it from f32 to f80.
12799   // FIXME: Avoid the extend by constructing the right constant pool?
12800   SDValue Fudge = DAG.getExtLoad(
12801       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12802       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12803       false, false, false, 4);
12804   // Extend everything to 80 bits to force it to be done on x87.
12805   // TODO: Are there any fast-math-flags to propagate here?
12806   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12807   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12808                      DAG.getIntPtrConstant(0, dl));
12809 }
12810
12811 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12812 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12813 // just return an <SDValue(), SDValue()> pair.
12814 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12815 // to i16, i32 or i64, and we lower it to a legal sequence.
12816 // If lowered to the final integer result we return a <result, SDValue()> pair.
12817 // Otherwise we lower it to a sequence ending with a FIST, return a
12818 // <FIST, StackSlot> pair, and the caller is responsible for loading
12819 // the final integer result from StackSlot.
12820 std::pair<SDValue,SDValue>
12821 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12822                                    bool IsSigned, bool IsReplace) const {
12823   SDLoc DL(Op);
12824
12825   EVT DstTy = Op.getValueType();
12826   EVT TheVT = Op.getOperand(0).getValueType();
12827   auto PtrVT = getPointerTy(DAG.getDataLayout());
12828
12829   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12830     // f16 must be promoted before using the lowering in this routine.
12831     // fp128 does not use this lowering.
12832     return std::make_pair(SDValue(), SDValue());
12833   }
12834
12835   // If using FIST to compute an unsigned i64, we'll need some fixup
12836   // to handle values above the maximum signed i64.  A FIST is always
12837   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12838   bool UnsignedFixup = !IsSigned &&
12839                        DstTy == MVT::i64 &&
12840                        (!Subtarget->is64Bit() ||
12841                         !isScalarFPTypeInSSEReg(TheVT));
12842
12843   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12844     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12845     // The low 32 bits of the fist result will have the correct uint32 result.
12846     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12847     DstTy = MVT::i64;
12848   }
12849
12850   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12851          DstTy.getSimpleVT() >= MVT::i16 &&
12852          "Unknown FP_TO_INT to lower!");
12853
12854   // These are really Legal.
12855   if (DstTy == MVT::i32 &&
12856       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12857     return std::make_pair(SDValue(), SDValue());
12858   if (Subtarget->is64Bit() &&
12859       DstTy == MVT::i64 &&
12860       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12861     return std::make_pair(SDValue(), SDValue());
12862
12863   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12864   // stack slot.
12865   MachineFunction &MF = DAG.getMachineFunction();
12866   unsigned MemSize = DstTy.getSizeInBits()/8;
12867   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12868   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12869
12870   unsigned Opc;
12871   switch (DstTy.getSimpleVT().SimpleTy) {
12872   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12873   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12874   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12875   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12876   }
12877
12878   SDValue Chain = DAG.getEntryNode();
12879   SDValue Value = Op.getOperand(0);
12880   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12881
12882   if (UnsignedFixup) {
12883     //
12884     // Conversion to unsigned i64 is implemented with a select,
12885     // depending on whether the source value fits in the range
12886     // of a signed i64.  Let Thresh be the FP equivalent of
12887     // 0x8000000000000000ULL.
12888     //
12889     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12890     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12891     //  Fist-to-mem64 FistSrc
12892     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12893     //  to XOR'ing the high 32 bits with Adjust.
12894     //
12895     // Being a power of 2, Thresh is exactly representable in all FP formats.
12896     // For X87 we'd like to use the smallest FP type for this constant, but
12897     // for DAG type consistency we have to match the FP operand type.
12898
12899     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12900     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12901     bool LosesInfo = false;
12902     if (TheVT == MVT::f64)
12903       // The rounding mode is irrelevant as the conversion should be exact.
12904       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12905                               &LosesInfo);
12906     else if (TheVT == MVT::f80)
12907       Status = Thresh.convert(APFloat::x87DoubleExtended,
12908                               APFloat::rmNearestTiesToEven, &LosesInfo);
12909
12910     assert(Status == APFloat::opOK && !LosesInfo &&
12911            "FP conversion should have been exact");
12912
12913     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12914
12915     SDValue Cmp = DAG.getSetCC(DL,
12916                                getSetCCResultType(DAG.getDataLayout(),
12917                                                   *DAG.getContext(), TheVT),
12918                                Value, ThreshVal, ISD::SETLT);
12919     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12920                            DAG.getConstant(0, DL, MVT::i32),
12921                            DAG.getConstant(0x80000000, DL, MVT::i32));
12922     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12923     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12924                                               *DAG.getContext(), TheVT),
12925                        Value, ThreshVal, ISD::SETLT);
12926     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12927   }
12928
12929   // FIXME This causes a redundant load/store if the SSE-class value is already
12930   // in memory, such as if it is on the callstack.
12931   if (isScalarFPTypeInSSEReg(TheVT)) {
12932     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12933     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12934                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12935                          false, 0);
12936     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12937     SDValue Ops[] = {
12938       Chain, StackSlot, DAG.getValueType(TheVT)
12939     };
12940
12941     MachineMemOperand *MMO =
12942         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12943                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12944     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12945     Chain = Value.getValue(1);
12946     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12947     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12948   }
12949
12950   MachineMemOperand *MMO =
12951       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12952                               MachineMemOperand::MOStore, MemSize, MemSize);
12953
12954   if (UnsignedFixup) {
12955
12956     // Insert the FIST, load its result as two i32's,
12957     // and XOR the high i32 with Adjust.
12958
12959     SDValue FistOps[] = { Chain, Value, StackSlot };
12960     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12961                                            FistOps, DstTy, MMO);
12962
12963     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12964                                 MachinePointerInfo(),
12965                                 false, false, false, 0);
12966     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12967                                    DAG.getConstant(4, DL, PtrVT));
12968
12969     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12970                                  MachinePointerInfo(),
12971                                  false, false, false, 0);
12972     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12973
12974     if (Subtarget->is64Bit()) {
12975       // Join High32 and Low32 into a 64-bit result.
12976       // (High32 << 32) | Low32
12977       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12978       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12979       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12980                            DAG.getConstant(32, DL, MVT::i8));
12981       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12982       return std::make_pair(Result, SDValue());
12983     }
12984
12985     SDValue ResultOps[] = { Low32, High32 };
12986
12987     SDValue pair = IsReplace
12988       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12989       : DAG.getMergeValues(ResultOps, DL);
12990     return std::make_pair(pair, SDValue());
12991   } else {
12992     // Build the FP_TO_INT*_IN_MEM
12993     SDValue Ops[] = { Chain, Value, StackSlot };
12994     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12995                                            Ops, DstTy, MMO);
12996     return std::make_pair(FIST, StackSlot);
12997   }
12998 }
12999
13000 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13001                               const X86Subtarget *Subtarget) {
13002   MVT VT = Op->getSimpleValueType(0);
13003   SDValue In = Op->getOperand(0);
13004   MVT InVT = In.getSimpleValueType();
13005   SDLoc dl(Op);
13006
13007   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13008     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13009
13010   // Optimize vectors in AVX mode:
13011   //
13012   //   v8i16 -> v8i32
13013   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13014   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13015   //   Concat upper and lower parts.
13016   //
13017   //   v4i32 -> v4i64
13018   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13019   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13020   //   Concat upper and lower parts.
13021   //
13022
13023   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13024       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13025       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13026     return SDValue();
13027
13028   if (Subtarget->hasInt256())
13029     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13030
13031   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13032   SDValue Undef = DAG.getUNDEF(InVT);
13033   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13034   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13035   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13036
13037   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13038                              VT.getVectorNumElements()/2);
13039
13040   OpLo = DAG.getBitcast(HVT, OpLo);
13041   OpHi = DAG.getBitcast(HVT, OpHi);
13042
13043   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13044 }
13045
13046 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13047                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13048   MVT VT = Op->getSimpleValueType(0);
13049   SDValue In = Op->getOperand(0);
13050   MVT InVT = In.getSimpleValueType();
13051   SDLoc DL(Op);
13052   unsigned int NumElts = VT.getVectorNumElements();
13053   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13054     return SDValue();
13055
13056   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13057     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13058
13059   assert(InVT.getVectorElementType() == MVT::i1);
13060   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13061   SDValue One =
13062    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13063   SDValue Zero =
13064    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13065
13066   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13067   if (VT.is512BitVector())
13068     return V;
13069   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13070 }
13071
13072 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13073                                SelectionDAG &DAG) {
13074   if (Subtarget->hasFp256())
13075     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13076       return Res;
13077
13078   return SDValue();
13079 }
13080
13081 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13082                                 SelectionDAG &DAG) {
13083   SDLoc DL(Op);
13084   MVT VT = Op.getSimpleValueType();
13085   SDValue In = Op.getOperand(0);
13086   MVT SVT = In.getSimpleValueType();
13087
13088   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13089     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13090
13091   if (Subtarget->hasFp256())
13092     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13093       return Res;
13094
13095   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13096          VT.getVectorNumElements() != SVT.getVectorNumElements());
13097   return SDValue();
13098 }
13099
13100 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13101   SDLoc DL(Op);
13102   MVT VT = Op.getSimpleValueType();
13103   SDValue In = Op.getOperand(0);
13104   MVT InVT = In.getSimpleValueType();
13105
13106   if (VT == MVT::i1) {
13107     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13108            "Invalid scalar TRUNCATE operation");
13109     if (InVT.getSizeInBits() >= 32)
13110       return SDValue();
13111     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13112     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13113   }
13114   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13115          "Invalid TRUNCATE operation");
13116
13117   // move vector to mask - truncate solution for SKX
13118   if (VT.getVectorElementType() == MVT::i1) {
13119     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13120         Subtarget->hasBWI())
13121       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13122     if ((InVT.is256BitVector() || InVT.is128BitVector())
13123         && InVT.getScalarSizeInBits() <= 16 &&
13124         Subtarget->hasBWI() && Subtarget->hasVLX())
13125       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13126     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13127         Subtarget->hasDQI())
13128       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13129     if ((InVT.is256BitVector() || InVT.is128BitVector())
13130         && InVT.getScalarSizeInBits() >= 32 &&
13131         Subtarget->hasDQI() && Subtarget->hasVLX())
13132       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13133   }
13134
13135   if (VT.getVectorElementType() == MVT::i1) {
13136     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13137     unsigned NumElts = InVT.getVectorNumElements();
13138     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13139     if (InVT.getSizeInBits() < 512) {
13140       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13141       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13142       InVT = ExtVT;
13143     }
13144
13145     SDValue OneV =
13146      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13147     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13148     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13149   }
13150
13151   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13152   if (Subtarget->hasAVX512()) {
13153     // word to byte only under BWI
13154     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13155       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13156                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13157     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13158   }
13159   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13160     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13161     if (Subtarget->hasInt256()) {
13162       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13163       In = DAG.getBitcast(MVT::v8i32, In);
13164       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13165                                 ShufMask);
13166       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13167                          DAG.getIntPtrConstant(0, DL));
13168     }
13169
13170     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13171                                DAG.getIntPtrConstant(0, DL));
13172     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13173                                DAG.getIntPtrConstant(2, DL));
13174     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13175     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13176     static const int ShufMask[] = {0, 2, 4, 6};
13177     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13178   }
13179
13180   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13181     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13182     if (Subtarget->hasInt256()) {
13183       In = DAG.getBitcast(MVT::v32i8, In);
13184
13185       SmallVector<SDValue,32> pshufbMask;
13186       for (unsigned i = 0; i < 2; ++i) {
13187         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13188         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13189         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13190         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13191         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13192         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13193         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13194         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13195         for (unsigned j = 0; j < 8; ++j)
13196           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13197       }
13198       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13199       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13200       In = DAG.getBitcast(MVT::v4i64, In);
13201
13202       static const int ShufMask[] = {0,  2,  -1,  -1};
13203       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13204                                 &ShufMask[0]);
13205       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13206                        DAG.getIntPtrConstant(0, DL));
13207       return DAG.getBitcast(VT, In);
13208     }
13209
13210     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13211                                DAG.getIntPtrConstant(0, DL));
13212
13213     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13214                                DAG.getIntPtrConstant(4, DL));
13215
13216     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13217     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13218
13219     // The PSHUFB mask:
13220     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13221                                    -1, -1, -1, -1, -1, -1, -1, -1};
13222
13223     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13224     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13225     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13226
13227     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13228     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13229
13230     // The MOVLHPS Mask:
13231     static const int ShufMask2[] = {0, 1, 4, 5};
13232     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13233     return DAG.getBitcast(MVT::v8i16, res);
13234   }
13235
13236   // Handle truncation of V256 to V128 using shuffles.
13237   if (!VT.is128BitVector() || !InVT.is256BitVector())
13238     return SDValue();
13239
13240   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13241
13242   unsigned NumElems = VT.getVectorNumElements();
13243   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13244
13245   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13246   // Prepare truncation shuffle mask
13247   for (unsigned i = 0; i != NumElems; ++i)
13248     MaskVec[i] = i * 2;
13249   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13250                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13251   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13252                      DAG.getIntPtrConstant(0, DL));
13253 }
13254
13255 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13256                                            SelectionDAG &DAG) const {
13257   assert(!Op.getSimpleValueType().isVector());
13258
13259   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13260     /*IsSigned=*/ true, /*IsReplace=*/ false);
13261   SDValue FIST = Vals.first, StackSlot = Vals.second;
13262   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13263   if (!FIST.getNode())
13264     return Op;
13265
13266   if (StackSlot.getNode())
13267     // Load the result.
13268     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13269                        FIST, StackSlot, MachinePointerInfo(),
13270                        false, false, false, 0);
13271
13272   // The node is the result.
13273   return FIST;
13274 }
13275
13276 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13277                                            SelectionDAG &DAG) const {
13278   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13279     /*IsSigned=*/ false, /*IsReplace=*/ false);
13280   SDValue FIST = Vals.first, StackSlot = Vals.second;
13281   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13282   if (!FIST.getNode())
13283     return Op;
13284
13285   if (StackSlot.getNode())
13286     // Load the result.
13287     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13288                        FIST, StackSlot, MachinePointerInfo(),
13289                        false, false, false, 0);
13290
13291   // The node is the result.
13292   return FIST;
13293 }
13294
13295 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13296   SDLoc DL(Op);
13297   MVT VT = Op.getSimpleValueType();
13298   SDValue In = Op.getOperand(0);
13299   MVT SVT = In.getSimpleValueType();
13300
13301   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13302
13303   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13304                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13305                                  In, DAG.getUNDEF(SVT)));
13306 }
13307
13308 /// The only differences between FABS and FNEG are the mask and the logic op.
13309 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13310 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13311   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13312          "Wrong opcode for lowering FABS or FNEG.");
13313
13314   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13315
13316   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13317   // into an FNABS. We'll lower the FABS after that if it is still in use.
13318   if (IsFABS)
13319     for (SDNode *User : Op->uses())
13320       if (User->getOpcode() == ISD::FNEG)
13321         return Op;
13322
13323   SDLoc dl(Op);
13324   MVT VT = Op.getSimpleValueType();
13325
13326   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13327   // decide if we should generate a 16-byte constant mask when we only need 4 or
13328   // 8 bytes for the scalar case.
13329
13330   MVT LogicVT;
13331   MVT EltVT;
13332   unsigned NumElts;
13333
13334   if (VT.isVector()) {
13335     LogicVT = VT;
13336     EltVT = VT.getVectorElementType();
13337     NumElts = VT.getVectorNumElements();
13338   } else {
13339     // There are no scalar bitwise logical SSE/AVX instructions, so we
13340     // generate a 16-byte vector constant and logic op even for the scalar case.
13341     // Using a 16-byte mask allows folding the load of the mask with
13342     // the logic op, so it can save (~4 bytes) on code size.
13343     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13344     EltVT = VT;
13345     NumElts = (VT == MVT::f64) ? 2 : 4;
13346   }
13347
13348   unsigned EltBits = EltVT.getSizeInBits();
13349   LLVMContext *Context = DAG.getContext();
13350   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13351   APInt MaskElt =
13352     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13353   Constant *C = ConstantInt::get(*Context, MaskElt);
13354   C = ConstantVector::getSplat(NumElts, C);
13355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13356   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13357   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13358   SDValue Mask =
13359       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13360                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13361                   false, false, false, Alignment);
13362
13363   SDValue Op0 = Op.getOperand(0);
13364   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13365   unsigned LogicOp =
13366     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13367   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13368
13369   if (VT.isVector())
13370     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13371
13372   // For the scalar case extend to a 128-bit vector, perform the logic op,
13373   // and extract the scalar result back out.
13374   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13375   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13376   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13377                      DAG.getIntPtrConstant(0, dl));
13378 }
13379
13380 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13382   LLVMContext *Context = DAG.getContext();
13383   SDValue Op0 = Op.getOperand(0);
13384   SDValue Op1 = Op.getOperand(1);
13385   SDLoc dl(Op);
13386   MVT VT = Op.getSimpleValueType();
13387   MVT SrcVT = Op1.getSimpleValueType();
13388
13389   // If second operand is smaller, extend it first.
13390   if (SrcVT.bitsLT(VT)) {
13391     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13392     SrcVT = VT;
13393   }
13394   // And if it is bigger, shrink it first.
13395   if (SrcVT.bitsGT(VT)) {
13396     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13397     SrcVT = VT;
13398   }
13399
13400   // At this point the operands and the result should have the same
13401   // type, and that won't be f80 since that is not custom lowered.
13402
13403   const fltSemantics &Sem =
13404       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13405   const unsigned SizeInBits = VT.getSizeInBits();
13406
13407   SmallVector<Constant *, 4> CV(
13408       VT == MVT::f64 ? 2 : 4,
13409       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13410
13411   // First, clear all bits but the sign bit from the second operand (sign).
13412   CV[0] = ConstantFP::get(*Context,
13413                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13414   Constant *C = ConstantVector::get(CV);
13415   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13416   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13417
13418   // Perform all logic operations as 16-byte vectors because there are no
13419   // scalar FP logic instructions in SSE. This allows load folding of the
13420   // constants into the logic instructions.
13421   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13422   SDValue Mask1 =
13423       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13424                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13425                   false, false, false, 16);
13426   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13427   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13428
13429   // Next, clear the sign bit from the first operand (magnitude).
13430   // If it's a constant, we can clear it here.
13431   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13432     APFloat APF = Op0CN->getValueAPF();
13433     // If the magnitude is a positive zero, the sign bit alone is enough.
13434     if (APF.isPosZero())
13435       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13436                          DAG.getIntPtrConstant(0, dl));
13437     APF.clearSign();
13438     CV[0] = ConstantFP::get(*Context, APF);
13439   } else {
13440     CV[0] = ConstantFP::get(
13441         *Context,
13442         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13443   }
13444   C = ConstantVector::get(CV);
13445   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13446   SDValue Val =
13447       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13448                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13449                   false, false, false, 16);
13450   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13451   if (!isa<ConstantFPSDNode>(Op0)) {
13452     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13453     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13454   }
13455   // OR the magnitude value with the sign bit.
13456   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13457   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13458                      DAG.getIntPtrConstant(0, dl));
13459 }
13460
13461 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13462   SDValue N0 = Op.getOperand(0);
13463   SDLoc dl(Op);
13464   MVT VT = Op.getSimpleValueType();
13465
13466   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13467   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13468                                   DAG.getConstant(1, dl, VT));
13469   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13470 }
13471
13472 // Check whether an OR'd tree is PTEST-able.
13473 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13474                                       SelectionDAG &DAG) {
13475   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13476
13477   if (!Subtarget->hasSSE41())
13478     return SDValue();
13479
13480   if (!Op->hasOneUse())
13481     return SDValue();
13482
13483   SDNode *N = Op.getNode();
13484   SDLoc DL(N);
13485
13486   SmallVector<SDValue, 8> Opnds;
13487   DenseMap<SDValue, unsigned> VecInMap;
13488   SmallVector<SDValue, 8> VecIns;
13489   EVT VT = MVT::Other;
13490
13491   // Recognize a special case where a vector is casted into wide integer to
13492   // test all 0s.
13493   Opnds.push_back(N->getOperand(0));
13494   Opnds.push_back(N->getOperand(1));
13495
13496   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13497     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13498     // BFS traverse all OR'd operands.
13499     if (I->getOpcode() == ISD::OR) {
13500       Opnds.push_back(I->getOperand(0));
13501       Opnds.push_back(I->getOperand(1));
13502       // Re-evaluate the number of nodes to be traversed.
13503       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13504       continue;
13505     }
13506
13507     // Quit if a non-EXTRACT_VECTOR_ELT
13508     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13509       return SDValue();
13510
13511     // Quit if without a constant index.
13512     SDValue Idx = I->getOperand(1);
13513     if (!isa<ConstantSDNode>(Idx))
13514       return SDValue();
13515
13516     SDValue ExtractedFromVec = I->getOperand(0);
13517     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13518     if (M == VecInMap.end()) {
13519       VT = ExtractedFromVec.getValueType();
13520       // Quit if not 128/256-bit vector.
13521       if (!VT.is128BitVector() && !VT.is256BitVector())
13522         return SDValue();
13523       // Quit if not the same type.
13524       if (VecInMap.begin() != VecInMap.end() &&
13525           VT != VecInMap.begin()->first.getValueType())
13526         return SDValue();
13527       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13528       VecIns.push_back(ExtractedFromVec);
13529     }
13530     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13531   }
13532
13533   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13534          "Not extracted from 128-/256-bit vector.");
13535
13536   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13537
13538   for (DenseMap<SDValue, unsigned>::const_iterator
13539         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13540     // Quit if not all elements are used.
13541     if (I->second != FullMask)
13542       return SDValue();
13543   }
13544
13545   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13546
13547   // Cast all vectors into TestVT for PTEST.
13548   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13549     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13550
13551   // If more than one full vectors are evaluated, OR them first before PTEST.
13552   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13553     // Each iteration will OR 2 nodes and append the result until there is only
13554     // 1 node left, i.e. the final OR'd value of all vectors.
13555     SDValue LHS = VecIns[Slot];
13556     SDValue RHS = VecIns[Slot + 1];
13557     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13558   }
13559
13560   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13561                      VecIns.back(), VecIns.back());
13562 }
13563
13564 /// \brief return true if \c Op has a use that doesn't just read flags.
13565 static bool hasNonFlagsUse(SDValue Op) {
13566   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13567        ++UI) {
13568     SDNode *User = *UI;
13569     unsigned UOpNo = UI.getOperandNo();
13570     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13571       // Look pass truncate.
13572       UOpNo = User->use_begin().getOperandNo();
13573       User = *User->use_begin();
13574     }
13575
13576     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13577         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13578       return true;
13579   }
13580   return false;
13581 }
13582
13583 /// Emit nodes that will be selected as "test Op0,Op0", or something
13584 /// equivalent.
13585 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13586                                     SelectionDAG &DAG) const {
13587   if (Op.getValueType() == MVT::i1) {
13588     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13589     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13590                        DAG.getConstant(0, dl, MVT::i8));
13591   }
13592   // CF and OF aren't always set the way we want. Determine which
13593   // of these we need.
13594   bool NeedCF = false;
13595   bool NeedOF = false;
13596   switch (X86CC) {
13597   default: break;
13598   case X86::COND_A: case X86::COND_AE:
13599   case X86::COND_B: case X86::COND_BE:
13600     NeedCF = true;
13601     break;
13602   case X86::COND_G: case X86::COND_GE:
13603   case X86::COND_L: case X86::COND_LE:
13604   case X86::COND_O: case X86::COND_NO: {
13605     // Check if we really need to set the
13606     // Overflow flag. If NoSignedWrap is present
13607     // that is not actually needed.
13608     switch (Op->getOpcode()) {
13609     case ISD::ADD:
13610     case ISD::SUB:
13611     case ISD::MUL:
13612     case ISD::SHL: {
13613       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13614       if (BinNode->Flags.hasNoSignedWrap())
13615         break;
13616     }
13617     default:
13618       NeedOF = true;
13619       break;
13620     }
13621     break;
13622   }
13623   }
13624   // See if we can use the EFLAGS value from the operand instead of
13625   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13626   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13627   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13628     // Emit a CMP with 0, which is the TEST pattern.
13629     //if (Op.getValueType() == MVT::i1)
13630     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13631     //                     DAG.getConstant(0, MVT::i1));
13632     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13633                        DAG.getConstant(0, dl, Op.getValueType()));
13634   }
13635   unsigned Opcode = 0;
13636   unsigned NumOperands = 0;
13637
13638   // Truncate operations may prevent the merge of the SETCC instruction
13639   // and the arithmetic instruction before it. Attempt to truncate the operands
13640   // of the arithmetic instruction and use a reduced bit-width instruction.
13641   bool NeedTruncation = false;
13642   SDValue ArithOp = Op;
13643   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13644     SDValue Arith = Op->getOperand(0);
13645     // Both the trunc and the arithmetic op need to have one user each.
13646     if (Arith->hasOneUse())
13647       switch (Arith.getOpcode()) {
13648         default: break;
13649         case ISD::ADD:
13650         case ISD::SUB:
13651         case ISD::AND:
13652         case ISD::OR:
13653         case ISD::XOR: {
13654           NeedTruncation = true;
13655           ArithOp = Arith;
13656         }
13657       }
13658   }
13659
13660   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13661   // which may be the result of a CAST.  We use the variable 'Op', which is the
13662   // non-casted variable when we check for possible users.
13663   switch (ArithOp.getOpcode()) {
13664   case ISD::ADD:
13665     // Due to an isel shortcoming, be conservative if this add is likely to be
13666     // selected as part of a load-modify-store instruction. When the root node
13667     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13668     // uses of other nodes in the match, such as the ADD in this case. This
13669     // leads to the ADD being left around and reselected, with the result being
13670     // two adds in the output.  Alas, even if none our users are stores, that
13671     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13672     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13673     // climbing the DAG back to the root, and it doesn't seem to be worth the
13674     // effort.
13675     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13676          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13677       if (UI->getOpcode() != ISD::CopyToReg &&
13678           UI->getOpcode() != ISD::SETCC &&
13679           UI->getOpcode() != ISD::STORE)
13680         goto default_case;
13681
13682     if (ConstantSDNode *C =
13683         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13684       // An add of one will be selected as an INC.
13685       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13686         Opcode = X86ISD::INC;
13687         NumOperands = 1;
13688         break;
13689       }
13690
13691       // An add of negative one (subtract of one) will be selected as a DEC.
13692       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13693         Opcode = X86ISD::DEC;
13694         NumOperands = 1;
13695         break;
13696       }
13697     }
13698
13699     // Otherwise use a regular EFLAGS-setting add.
13700     Opcode = X86ISD::ADD;
13701     NumOperands = 2;
13702     break;
13703   case ISD::SHL:
13704   case ISD::SRL:
13705     // If we have a constant logical shift that's only used in a comparison
13706     // against zero turn it into an equivalent AND. This allows turning it into
13707     // a TEST instruction later.
13708     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13709         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13710       EVT VT = Op.getValueType();
13711       unsigned BitWidth = VT.getSizeInBits();
13712       unsigned ShAmt = Op->getConstantOperandVal(1);
13713       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13714         break;
13715       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13716                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13717                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13718       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13719         break;
13720       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13721                                 DAG.getConstant(Mask, dl, VT));
13722       DAG.ReplaceAllUsesWith(Op, New);
13723       Op = New;
13724     }
13725     break;
13726
13727   case ISD::AND:
13728     // If the primary and result isn't used, don't bother using X86ISD::AND,
13729     // because a TEST instruction will be better.
13730     if (!hasNonFlagsUse(Op))
13731       break;
13732     // FALL THROUGH
13733   case ISD::SUB:
13734   case ISD::OR:
13735   case ISD::XOR:
13736     // Due to the ISEL shortcoming noted above, be conservative if this op is
13737     // likely to be selected as part of a load-modify-store instruction.
13738     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13739            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13740       if (UI->getOpcode() == ISD::STORE)
13741         goto default_case;
13742
13743     // Otherwise use a regular EFLAGS-setting instruction.
13744     switch (ArithOp.getOpcode()) {
13745     default: llvm_unreachable("unexpected operator!");
13746     case ISD::SUB: Opcode = X86ISD::SUB; break;
13747     case ISD::XOR: Opcode = X86ISD::XOR; break;
13748     case ISD::AND: Opcode = X86ISD::AND; break;
13749     case ISD::OR: {
13750       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13751         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13752         if (EFLAGS.getNode())
13753           return EFLAGS;
13754       }
13755       Opcode = X86ISD::OR;
13756       break;
13757     }
13758     }
13759
13760     NumOperands = 2;
13761     break;
13762   case X86ISD::ADD:
13763   case X86ISD::SUB:
13764   case X86ISD::INC:
13765   case X86ISD::DEC:
13766   case X86ISD::OR:
13767   case X86ISD::XOR:
13768   case X86ISD::AND:
13769     return SDValue(Op.getNode(), 1);
13770   default:
13771   default_case:
13772     break;
13773   }
13774
13775   // If we found that truncation is beneficial, perform the truncation and
13776   // update 'Op'.
13777   if (NeedTruncation) {
13778     EVT VT = Op.getValueType();
13779     SDValue WideVal = Op->getOperand(0);
13780     EVT WideVT = WideVal.getValueType();
13781     unsigned ConvertedOp = 0;
13782     // Use a target machine opcode to prevent further DAGCombine
13783     // optimizations that may separate the arithmetic operations
13784     // from the setcc node.
13785     switch (WideVal.getOpcode()) {
13786       default: break;
13787       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13788       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13789       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13790       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13791       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13792     }
13793
13794     if (ConvertedOp) {
13795       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13796       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13797         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13798         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13799         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13800       }
13801     }
13802   }
13803
13804   if (Opcode == 0)
13805     // Emit a CMP with 0, which is the TEST pattern.
13806     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13807                        DAG.getConstant(0, dl, Op.getValueType()));
13808
13809   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13810   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13811
13812   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13813   DAG.ReplaceAllUsesWith(Op, New);
13814   return SDValue(New.getNode(), 1);
13815 }
13816
13817 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13818 /// equivalent.
13819 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13820                                    SDLoc dl, SelectionDAG &DAG) const {
13821   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13822     if (C->getAPIntValue() == 0)
13823       return EmitTest(Op0, X86CC, dl, DAG);
13824
13825      assert(Op0.getValueType() != MVT::i1 &&
13826             "Unexpected comparison operation for MVT::i1 operands");
13827   }
13828
13829   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13830        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13831     // Do the comparison at i32 if it's smaller, besides the Atom case.
13832     // This avoids subregister aliasing issues. Keep the smaller reference
13833     // if we're optimizing for size, however, as that'll allow better folding
13834     // of memory operations.
13835     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13836         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13837         !Subtarget->isAtom()) {
13838       unsigned ExtendOp =
13839           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13840       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13841       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13842     }
13843     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13844     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13845     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13846                               Op0, Op1);
13847     return SDValue(Sub.getNode(), 1);
13848   }
13849   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13850 }
13851
13852 /// Convert a comparison if required by the subtarget.
13853 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13854                                                  SelectionDAG &DAG) const {
13855   // If the subtarget does not support the FUCOMI instruction, floating-point
13856   // comparisons have to be converted.
13857   if (Subtarget->hasCMov() ||
13858       Cmp.getOpcode() != X86ISD::CMP ||
13859       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13860       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13861     return Cmp;
13862
13863   // The instruction selector will select an FUCOM instruction instead of
13864   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13865   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13866   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13867   SDLoc dl(Cmp);
13868   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13869   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13870   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13871                             DAG.getConstant(8, dl, MVT::i8));
13872   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13873   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13874 }
13875
13876 /// The minimum architected relative accuracy is 2^-12. We need one
13877 /// Newton-Raphson step to have a good float result (24 bits of precision).
13878 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13879                                             DAGCombinerInfo &DCI,
13880                                             unsigned &RefinementSteps,
13881                                             bool &UseOneConstNR) const {
13882   EVT VT = Op.getValueType();
13883   const char *RecipOp;
13884
13885   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13886   // TODO: Add support for AVX512 (v16f32).
13887   // It is likely not profitable to do this for f64 because a double-precision
13888   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13889   // instructions: convert to single, rsqrtss, convert back to double, refine
13890   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13891   // along with FMA, this could be a throughput win.
13892   if (VT == MVT::f32 && Subtarget->hasSSE1())
13893     RecipOp = "sqrtf";
13894   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13895            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13896     RecipOp = "vec-sqrtf";
13897   else
13898     return SDValue();
13899
13900   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13901   if (!Recips.isEnabled(RecipOp))
13902     return SDValue();
13903
13904   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13905   UseOneConstNR = false;
13906   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13907 }
13908
13909 /// The minimum architected relative accuracy is 2^-12. We need one
13910 /// Newton-Raphson step to have a good float result (24 bits of precision).
13911 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13912                                             DAGCombinerInfo &DCI,
13913                                             unsigned &RefinementSteps) const {
13914   EVT VT = Op.getValueType();
13915   const char *RecipOp;
13916
13917   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13918   // TODO: Add support for AVX512 (v16f32).
13919   // It is likely not profitable to do this for f64 because a double-precision
13920   // reciprocal estimate with refinement on x86 prior to FMA requires
13921   // 15 instructions: convert to single, rcpss, convert back to double, refine
13922   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13923   // along with FMA, this could be a throughput win.
13924   if (VT == MVT::f32 && Subtarget->hasSSE1())
13925     RecipOp = "divf";
13926   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13927            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13928     RecipOp = "vec-divf";
13929   else
13930     return SDValue();
13931
13932   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13933   if (!Recips.isEnabled(RecipOp))
13934     return SDValue();
13935
13936   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13937   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13938 }
13939
13940 /// If we have at least two divisions that use the same divisor, convert to
13941 /// multplication by a reciprocal. This may need to be adjusted for a given
13942 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13943 /// This is because we still need one division to calculate the reciprocal and
13944 /// then we need two multiplies by that reciprocal as replacements for the
13945 /// original divisions.
13946 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13947   return 2;
13948 }
13949
13950 static bool isAllOnes(SDValue V) {
13951   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13952   return C && C->isAllOnesValue();
13953 }
13954
13955 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13956 /// if it's possible.
13957 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13958                                      SDLoc dl, SelectionDAG &DAG) const {
13959   SDValue Op0 = And.getOperand(0);
13960   SDValue Op1 = And.getOperand(1);
13961   if (Op0.getOpcode() == ISD::TRUNCATE)
13962     Op0 = Op0.getOperand(0);
13963   if (Op1.getOpcode() == ISD::TRUNCATE)
13964     Op1 = Op1.getOperand(0);
13965
13966   SDValue LHS, RHS;
13967   if (Op1.getOpcode() == ISD::SHL)
13968     std::swap(Op0, Op1);
13969   if (Op0.getOpcode() == ISD::SHL) {
13970     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13971       if (And00C->getZExtValue() == 1) {
13972         // If we looked past a truncate, check that it's only truncating away
13973         // known zeros.
13974         unsigned BitWidth = Op0.getValueSizeInBits();
13975         unsigned AndBitWidth = And.getValueSizeInBits();
13976         if (BitWidth > AndBitWidth) {
13977           APInt Zeros, Ones;
13978           DAG.computeKnownBits(Op0, Zeros, Ones);
13979           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13980             return SDValue();
13981         }
13982         LHS = Op1;
13983         RHS = Op0.getOperand(1);
13984       }
13985   } else if (Op1.getOpcode() == ISD::Constant) {
13986     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13987     uint64_t AndRHSVal = AndRHS->getZExtValue();
13988     SDValue AndLHS = Op0;
13989
13990     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13991       LHS = AndLHS.getOperand(0);
13992       RHS = AndLHS.getOperand(1);
13993     }
13994
13995     // Use BT if the immediate can't be encoded in a TEST instruction.
13996     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13997       LHS = AndLHS;
13998       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13999     }
14000   }
14001
14002   if (LHS.getNode()) {
14003     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14004     // instruction.  Since the shift amount is in-range-or-undefined, we know
14005     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14006     // the encoding for the i16 version is larger than the i32 version.
14007     // Also promote i16 to i32 for performance / code size reason.
14008     if (LHS.getValueType() == MVT::i8 ||
14009         LHS.getValueType() == MVT::i16)
14010       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14011
14012     // If the operand types disagree, extend the shift amount to match.  Since
14013     // BT ignores high bits (like shifts) we can use anyextend.
14014     if (LHS.getValueType() != RHS.getValueType())
14015       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14016
14017     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14018     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14019     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14020                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14021   }
14022
14023   return SDValue();
14024 }
14025
14026 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14027 /// mask CMPs.
14028 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14029                               SDValue &Op1) {
14030   unsigned SSECC;
14031   bool Swap = false;
14032
14033   // SSE Condition code mapping:
14034   //  0 - EQ
14035   //  1 - LT
14036   //  2 - LE
14037   //  3 - UNORD
14038   //  4 - NEQ
14039   //  5 - NLT
14040   //  6 - NLE
14041   //  7 - ORD
14042   switch (SetCCOpcode) {
14043   default: llvm_unreachable("Unexpected SETCC condition");
14044   case ISD::SETOEQ:
14045   case ISD::SETEQ:  SSECC = 0; break;
14046   case ISD::SETOGT:
14047   case ISD::SETGT:  Swap = true; // Fallthrough
14048   case ISD::SETLT:
14049   case ISD::SETOLT: SSECC = 1; break;
14050   case ISD::SETOGE:
14051   case ISD::SETGE:  Swap = true; // Fallthrough
14052   case ISD::SETLE:
14053   case ISD::SETOLE: SSECC = 2; break;
14054   case ISD::SETUO:  SSECC = 3; break;
14055   case ISD::SETUNE:
14056   case ISD::SETNE:  SSECC = 4; break;
14057   case ISD::SETULE: Swap = true; // Fallthrough
14058   case ISD::SETUGE: SSECC = 5; break;
14059   case ISD::SETULT: Swap = true; // Fallthrough
14060   case ISD::SETUGT: SSECC = 6; break;
14061   case ISD::SETO:   SSECC = 7; break;
14062   case ISD::SETUEQ:
14063   case ISD::SETONE: SSECC = 8; break;
14064   }
14065   if (Swap)
14066     std::swap(Op0, Op1);
14067
14068   return SSECC;
14069 }
14070
14071 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14072 // ones, and then concatenate the result back.
14073 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14074   MVT VT = Op.getSimpleValueType();
14075
14076   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14077          "Unsupported value type for operation");
14078
14079   unsigned NumElems = VT.getVectorNumElements();
14080   SDLoc dl(Op);
14081   SDValue CC = Op.getOperand(2);
14082
14083   // Extract the LHS vectors
14084   SDValue LHS = Op.getOperand(0);
14085   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14086   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14087
14088   // Extract the RHS vectors
14089   SDValue RHS = Op.getOperand(1);
14090   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14091   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14092
14093   // Issue the operation on the smaller types and concatenate the result back
14094   MVT EltVT = VT.getVectorElementType();
14095   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14096   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14097                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14098                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14099 }
14100
14101 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14102   SDValue Op0 = Op.getOperand(0);
14103   SDValue Op1 = Op.getOperand(1);
14104   SDValue CC = Op.getOperand(2);
14105   MVT VT = Op.getSimpleValueType();
14106   SDLoc dl(Op);
14107
14108   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14109          "Unexpected type for boolean compare operation");
14110   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14111   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14112                                DAG.getConstant(-1, dl, VT));
14113   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14114                                DAG.getConstant(-1, dl, VT));
14115   switch (SetCCOpcode) {
14116   default: llvm_unreachable("Unexpected SETCC condition");
14117   case ISD::SETEQ:
14118     // (x == y) -> ~(x ^ y)
14119     return DAG.getNode(ISD::XOR, dl, VT,
14120                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14121                        DAG.getConstant(-1, dl, VT));
14122   case ISD::SETNE:
14123     // (x != y) -> (x ^ y)
14124     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14125   case ISD::SETUGT:
14126   case ISD::SETGT:
14127     // (x > y) -> (x & ~y)
14128     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14129   case ISD::SETULT:
14130   case ISD::SETLT:
14131     // (x < y) -> (~x & y)
14132     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14133   case ISD::SETULE:
14134   case ISD::SETLE:
14135     // (x <= y) -> (~x | y)
14136     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14137   case ISD::SETUGE:
14138   case ISD::SETGE:
14139     // (x >=y) -> (x | ~y)
14140     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14141   }
14142 }
14143
14144 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14145                                      const X86Subtarget *Subtarget) {
14146   SDValue Op0 = Op.getOperand(0);
14147   SDValue Op1 = Op.getOperand(1);
14148   SDValue CC = Op.getOperand(2);
14149   MVT VT = Op.getSimpleValueType();
14150   SDLoc dl(Op);
14151
14152   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14153          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14154          "Cannot set masked compare for this operation");
14155
14156   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14157   unsigned  Opc = 0;
14158   bool Unsigned = false;
14159   bool Swap = false;
14160   unsigned SSECC;
14161   switch (SetCCOpcode) {
14162   default: llvm_unreachable("Unexpected SETCC condition");
14163   case ISD::SETNE:  SSECC = 4; break;
14164   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14165   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14166   case ISD::SETLT:  Swap = true; //fall-through
14167   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14168   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14169   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14170   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14171   case ISD::SETULE: Unsigned = true; //fall-through
14172   case ISD::SETLE:  SSECC = 2; break;
14173   }
14174
14175   if (Swap)
14176     std::swap(Op0, Op1);
14177   if (Opc)
14178     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14179   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14180   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14181                      DAG.getConstant(SSECC, dl, MVT::i8));
14182 }
14183
14184 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14185 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14186 /// return an empty value.
14187 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14188 {
14189   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14190   if (!BV)
14191     return SDValue();
14192
14193   MVT VT = Op1.getSimpleValueType();
14194   MVT EVT = VT.getVectorElementType();
14195   unsigned n = VT.getVectorNumElements();
14196   SmallVector<SDValue, 8> ULTOp1;
14197
14198   for (unsigned i = 0; i < n; ++i) {
14199     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14200     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14201       return SDValue();
14202
14203     // Avoid underflow.
14204     APInt Val = Elt->getAPIntValue();
14205     if (Val == 0)
14206       return SDValue();
14207
14208     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14209   }
14210
14211   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14212 }
14213
14214 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14215                            SelectionDAG &DAG) {
14216   SDValue Op0 = Op.getOperand(0);
14217   SDValue Op1 = Op.getOperand(1);
14218   SDValue CC = Op.getOperand(2);
14219   MVT VT = Op.getSimpleValueType();
14220   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14221   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14222   SDLoc dl(Op);
14223
14224   if (isFP) {
14225 #ifndef NDEBUG
14226     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14227     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14228 #endif
14229
14230     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14231     unsigned Opc = X86ISD::CMPP;
14232     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14233       assert(VT.getVectorNumElements() <= 16);
14234       Opc = X86ISD::CMPM;
14235     }
14236     // In the two special cases we can't handle, emit two comparisons.
14237     if (SSECC == 8) {
14238       unsigned CC0, CC1;
14239       unsigned CombineOpc;
14240       if (SetCCOpcode == ISD::SETUEQ) {
14241         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14242       } else {
14243         assert(SetCCOpcode == ISD::SETONE);
14244         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14245       }
14246
14247       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14248                                  DAG.getConstant(CC0, dl, MVT::i8));
14249       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14250                                  DAG.getConstant(CC1, dl, MVT::i8));
14251       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14252     }
14253     // Handle all other FP comparisons here.
14254     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14255                        DAG.getConstant(SSECC, dl, MVT::i8));
14256   }
14257
14258   MVT VTOp0 = Op0.getSimpleValueType();
14259   assert(VTOp0 == Op1.getSimpleValueType() &&
14260          "Expected operands with same type!");
14261   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14262          "Invalid number of packed elements for source and destination!");
14263
14264   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14265     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14266     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14267     // legalizer firstly checks if the first operand in input to the setcc has
14268     // a legal type. If so, then it promotes the return type to that same type.
14269     // Otherwise, the return type is promoted to the 'next legal type' which,
14270     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14271     //
14272     // We reach this code only if the following two conditions are met:
14273     // 1. Both return type and operand type have been promoted to wider types
14274     //    by the type legalizer.
14275     // 2. The original operand type has been promoted to a 256-bit vector.
14276     //
14277     // Note that condition 2. only applies for AVX targets.
14278     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14279     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14280   }
14281
14282   // The non-AVX512 code below works under the assumption that source and
14283   // destination types are the same.
14284   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14285          "Value types for source and destination must be the same!");
14286
14287   // Break 256-bit integer vector compare into smaller ones.
14288   if (VT.is256BitVector() && !Subtarget->hasInt256())
14289     return Lower256IntVSETCC(Op, DAG);
14290
14291   MVT OpVT = Op1.getSimpleValueType();
14292   if (OpVT.getVectorElementType() == MVT::i1)
14293     return LowerBoolVSETCC_AVX512(Op, DAG);
14294
14295   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14296   if (Subtarget->hasAVX512()) {
14297     if (Op1.getSimpleValueType().is512BitVector() ||
14298         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14299         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14300       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14301
14302     // In AVX-512 architecture setcc returns mask with i1 elements,
14303     // But there is no compare instruction for i8 and i16 elements in KNL.
14304     // We are not talking about 512-bit operands in this case, these
14305     // types are illegal.
14306     if (MaskResult &&
14307         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14308          OpVT.getVectorElementType().getSizeInBits() >= 8))
14309       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14310                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14311   }
14312
14313   // Lower using XOP integer comparisons.
14314   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14315        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14316     // Translate compare code to XOP PCOM compare mode.
14317     unsigned CmpMode = 0;
14318     switch (SetCCOpcode) {
14319     default: llvm_unreachable("Unexpected SETCC condition");
14320     case ISD::SETULT:
14321     case ISD::SETLT: CmpMode = 0x00; break;
14322     case ISD::SETULE:
14323     case ISD::SETLE: CmpMode = 0x01; break;
14324     case ISD::SETUGT:
14325     case ISD::SETGT: CmpMode = 0x02; break;
14326     case ISD::SETUGE:
14327     case ISD::SETGE: CmpMode = 0x03; break;
14328     case ISD::SETEQ: CmpMode = 0x04; break;
14329     case ISD::SETNE: CmpMode = 0x05; break;
14330     }
14331
14332     // Are we comparing unsigned or signed integers?
14333     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14334       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14335
14336     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14337                        DAG.getConstant(CmpMode, dl, MVT::i8));
14338   }
14339
14340   // We are handling one of the integer comparisons here.  Since SSE only has
14341   // GT and EQ comparisons for integer, swapping operands and multiple
14342   // operations may be required for some comparisons.
14343   unsigned Opc;
14344   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14345   bool Subus = false;
14346
14347   switch (SetCCOpcode) {
14348   default: llvm_unreachable("Unexpected SETCC condition");
14349   case ISD::SETNE:  Invert = true;
14350   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14351   case ISD::SETLT:  Swap = true;
14352   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14353   case ISD::SETGE:  Swap = true;
14354   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14355                     Invert = true; break;
14356   case ISD::SETULT: Swap = true;
14357   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14358                     FlipSigns = true; break;
14359   case ISD::SETUGE: Swap = true;
14360   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14361                     FlipSigns = true; Invert = true; break;
14362   }
14363
14364   // Special case: Use min/max operations for SETULE/SETUGE
14365   MVT VET = VT.getVectorElementType();
14366   bool hasMinMax =
14367        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14368     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14369
14370   if (hasMinMax) {
14371     switch (SetCCOpcode) {
14372     default: break;
14373     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14374     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14375     }
14376
14377     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14378   }
14379
14380   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14381   if (!MinMax && hasSubus) {
14382     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14383     // Op0 u<= Op1:
14384     //   t = psubus Op0, Op1
14385     //   pcmpeq t, <0..0>
14386     switch (SetCCOpcode) {
14387     default: break;
14388     case ISD::SETULT: {
14389       // If the comparison is against a constant we can turn this into a
14390       // setule.  With psubus, setule does not require a swap.  This is
14391       // beneficial because the constant in the register is no longer
14392       // destructed as the destination so it can be hoisted out of a loop.
14393       // Only do this pre-AVX since vpcmp* is no longer destructive.
14394       if (Subtarget->hasAVX())
14395         break;
14396       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14397       if (ULEOp1.getNode()) {
14398         Op1 = ULEOp1;
14399         Subus = true; Invert = false; Swap = false;
14400       }
14401       break;
14402     }
14403     // Psubus is better than flip-sign because it requires no inversion.
14404     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14405     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14406     }
14407
14408     if (Subus) {
14409       Opc = X86ISD::SUBUS;
14410       FlipSigns = false;
14411     }
14412   }
14413
14414   if (Swap)
14415     std::swap(Op0, Op1);
14416
14417   // Check that the operation in question is available (most are plain SSE2,
14418   // but PCMPGTQ and PCMPEQQ have different requirements).
14419   if (VT == MVT::v2i64) {
14420     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14421       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14422
14423       // First cast everything to the right type.
14424       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14425       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14426
14427       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14428       // bits of the inputs before performing those operations. The lower
14429       // compare is always unsigned.
14430       SDValue SB;
14431       if (FlipSigns) {
14432         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14433       } else {
14434         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14435         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14436         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14437                          Sign, Zero, Sign, Zero);
14438       }
14439       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14440       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14441
14442       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14443       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14444       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14445
14446       // Create masks for only the low parts/high parts of the 64 bit integers.
14447       static const int MaskHi[] = { 1, 1, 3, 3 };
14448       static const int MaskLo[] = { 0, 0, 2, 2 };
14449       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14450       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14451       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14452
14453       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14454       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14455
14456       if (Invert)
14457         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14458
14459       return DAG.getBitcast(VT, Result);
14460     }
14461
14462     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14463       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14464       // pcmpeqd + pshufd + pand.
14465       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14466
14467       // First cast everything to the right type.
14468       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14469       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14470
14471       // Do the compare.
14472       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14473
14474       // Make sure the lower and upper halves are both all-ones.
14475       static const int Mask[] = { 1, 0, 3, 2 };
14476       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14477       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14478
14479       if (Invert)
14480         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14481
14482       return DAG.getBitcast(VT, Result);
14483     }
14484   }
14485
14486   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14487   // bits of the inputs before performing those operations.
14488   if (FlipSigns) {
14489     MVT EltVT = VT.getVectorElementType();
14490     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14491                                  VT);
14492     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14493     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14494   }
14495
14496   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14497
14498   // If the logical-not of the result is required, perform that now.
14499   if (Invert)
14500     Result = DAG.getNOT(dl, Result, VT);
14501
14502   if (MinMax)
14503     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14504
14505   if (Subus)
14506     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14507                          getZeroVector(VT, Subtarget, DAG, dl));
14508
14509   return Result;
14510 }
14511
14512 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14513
14514   MVT VT = Op.getSimpleValueType();
14515
14516   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14517
14518   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14519          && "SetCC type must be 8-bit or 1-bit integer");
14520   SDValue Op0 = Op.getOperand(0);
14521   SDValue Op1 = Op.getOperand(1);
14522   SDLoc dl(Op);
14523   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14524
14525   // Optimize to BT if possible.
14526   // Lower (X & (1 << N)) == 0 to BT(X, N).
14527   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14528   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14529   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14530       Op1.getOpcode() == ISD::Constant &&
14531       cast<ConstantSDNode>(Op1)->isNullValue() &&
14532       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14533     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14534       if (VT == MVT::i1)
14535         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14536       return NewSetCC;
14537     }
14538   }
14539
14540   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14541   // these.
14542   if (Op1.getOpcode() == ISD::Constant &&
14543       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14544        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14545       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14546
14547     // If the input is a setcc, then reuse the input setcc or use a new one with
14548     // the inverted condition.
14549     if (Op0.getOpcode() == X86ISD::SETCC) {
14550       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14551       bool Invert = (CC == ISD::SETNE) ^
14552         cast<ConstantSDNode>(Op1)->isNullValue();
14553       if (!Invert)
14554         return Op0;
14555
14556       CCode = X86::GetOppositeBranchCondition(CCode);
14557       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14558                                   DAG.getConstant(CCode, dl, MVT::i8),
14559                                   Op0.getOperand(1));
14560       if (VT == MVT::i1)
14561         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14562       return SetCC;
14563     }
14564   }
14565   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14566       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14567       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14568
14569     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14570     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14571   }
14572
14573   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14574   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14575   if (X86CC == X86::COND_INVALID)
14576     return SDValue();
14577
14578   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14579   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14580   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14581                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14582   if (VT == MVT::i1)
14583     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14584   return SetCC;
14585 }
14586
14587 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14588   SDValue LHS = Op.getOperand(0);
14589   SDValue RHS = Op.getOperand(1);
14590   SDValue Carry = Op.getOperand(2);
14591   SDValue Cond = Op.getOperand(3);
14592   SDLoc DL(Op);
14593
14594   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14595   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14596
14597   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14598   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14599   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14600   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14601                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14602 }
14603
14604 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14605 static bool isX86LogicalCmp(SDValue Op) {
14606   unsigned Opc = Op.getNode()->getOpcode();
14607   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14608       Opc == X86ISD::SAHF)
14609     return true;
14610   if (Op.getResNo() == 1 &&
14611       (Opc == X86ISD::ADD ||
14612        Opc == X86ISD::SUB ||
14613        Opc == X86ISD::ADC ||
14614        Opc == X86ISD::SBB ||
14615        Opc == X86ISD::SMUL ||
14616        Opc == X86ISD::UMUL ||
14617        Opc == X86ISD::INC ||
14618        Opc == X86ISD::DEC ||
14619        Opc == X86ISD::OR ||
14620        Opc == X86ISD::XOR ||
14621        Opc == X86ISD::AND))
14622     return true;
14623
14624   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14625     return true;
14626
14627   return false;
14628 }
14629
14630 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14631   if (V.getOpcode() != ISD::TRUNCATE)
14632     return false;
14633
14634   SDValue VOp0 = V.getOperand(0);
14635   unsigned InBits = VOp0.getValueSizeInBits();
14636   unsigned Bits = V.getValueSizeInBits();
14637   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14638 }
14639
14640 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14641   bool addTest = true;
14642   SDValue Cond  = Op.getOperand(0);
14643   SDValue Op1 = Op.getOperand(1);
14644   SDValue Op2 = Op.getOperand(2);
14645   SDLoc DL(Op);
14646   MVT VT = Op1.getSimpleValueType();
14647   SDValue CC;
14648
14649   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14650   // are available or VBLENDV if AVX is available.
14651   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14652   if (Cond.getOpcode() == ISD::SETCC &&
14653       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14654        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14655       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14656     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14657     int SSECC = translateX86FSETCC(
14658         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14659
14660     if (SSECC != 8) {
14661       if (Subtarget->hasAVX512()) {
14662         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14663                                   DAG.getConstant(SSECC, DL, MVT::i8));
14664         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14665       }
14666
14667       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14668                                 DAG.getConstant(SSECC, DL, MVT::i8));
14669
14670       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14671       // of 3 logic instructions for size savings and potentially speed.
14672       // Unfortunately, there is no scalar form of VBLENDV.
14673
14674       // If either operand is a constant, don't try this. We can expect to
14675       // optimize away at least one of the logic instructions later in that
14676       // case, so that sequence would be faster than a variable blend.
14677
14678       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14679       // uses XMM0 as the selection register. That may need just as many
14680       // instructions as the AND/ANDN/OR sequence due to register moves, so
14681       // don't bother.
14682
14683       if (Subtarget->hasAVX() &&
14684           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14685
14686         // Convert to vectors, do a VSELECT, and convert back to scalar.
14687         // All of the conversions should be optimized away.
14688
14689         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14690         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14691         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14692         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14693
14694         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14695         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14696
14697         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14698
14699         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14700                            VSel, DAG.getIntPtrConstant(0, DL));
14701       }
14702       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14703       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14704       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14705     }
14706   }
14707
14708   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14709     SDValue Op1Scalar;
14710     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14711       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14712     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14713       Op1Scalar = Op1.getOperand(0);
14714     SDValue Op2Scalar;
14715     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14716       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14717     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14718       Op2Scalar = Op2.getOperand(0);
14719     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14720       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14721                                       Op1Scalar.getValueType(),
14722                                       Cond, Op1Scalar, Op2Scalar);
14723       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14724         return DAG.getBitcast(VT, newSelect);
14725       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14726       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14727                          DAG.getIntPtrConstant(0, DL));
14728     }
14729   }
14730
14731   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14732     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14733     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14734                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14735     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14736                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14737     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14738                                     Cond, Op1, Op2);
14739     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14740   }
14741
14742   if (Cond.getOpcode() == ISD::SETCC) {
14743     SDValue NewCond = LowerSETCC(Cond, DAG);
14744     if (NewCond.getNode())
14745       Cond = NewCond;
14746   }
14747
14748   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14749   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14750   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14751   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14752   if (Cond.getOpcode() == X86ISD::SETCC &&
14753       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14754       isZero(Cond.getOperand(1).getOperand(1))) {
14755     SDValue Cmp = Cond.getOperand(1);
14756
14757     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14758
14759     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14760         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14761       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14762
14763       SDValue CmpOp0 = Cmp.getOperand(0);
14764       // Apply further optimizations for special cases
14765       // (select (x != 0), -1, 0) -> neg & sbb
14766       // (select (x == 0), 0, -1) -> neg & sbb
14767       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14768         if (YC->isNullValue() &&
14769             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14770           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14771           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14772                                     DAG.getConstant(0, DL,
14773                                                     CmpOp0.getValueType()),
14774                                     CmpOp0);
14775           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14776                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14777                                     SDValue(Neg.getNode(), 1));
14778           return Res;
14779         }
14780
14781       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14782                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14783       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14784
14785       SDValue Res =   // Res = 0 or -1.
14786         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14787                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14788
14789       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14790         Res = DAG.getNOT(DL, Res, Res.getValueType());
14791
14792       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14793       if (!N2C || !N2C->isNullValue())
14794         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14795       return Res;
14796     }
14797   }
14798
14799   // Look past (and (setcc_carry (cmp ...)), 1).
14800   if (Cond.getOpcode() == ISD::AND &&
14801       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14802     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14803     if (C && C->getAPIntValue() == 1)
14804       Cond = Cond.getOperand(0);
14805   }
14806
14807   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14808   // setting operand in place of the X86ISD::SETCC.
14809   unsigned CondOpcode = Cond.getOpcode();
14810   if (CondOpcode == X86ISD::SETCC ||
14811       CondOpcode == X86ISD::SETCC_CARRY) {
14812     CC = Cond.getOperand(0);
14813
14814     SDValue Cmp = Cond.getOperand(1);
14815     unsigned Opc = Cmp.getOpcode();
14816     MVT VT = Op.getSimpleValueType();
14817
14818     bool IllegalFPCMov = false;
14819     if (VT.isFloatingPoint() && !VT.isVector() &&
14820         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14821       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14822
14823     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14824         Opc == X86ISD::BT) { // FIXME
14825       Cond = Cmp;
14826       addTest = false;
14827     }
14828   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14829              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14830              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14831               Cond.getOperand(0).getValueType() != MVT::i8)) {
14832     SDValue LHS = Cond.getOperand(0);
14833     SDValue RHS = Cond.getOperand(1);
14834     unsigned X86Opcode;
14835     unsigned X86Cond;
14836     SDVTList VTs;
14837     switch (CondOpcode) {
14838     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14839     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14840     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14841     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14842     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14843     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14844     default: llvm_unreachable("unexpected overflowing operator");
14845     }
14846     if (CondOpcode == ISD::UMULO)
14847       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14848                           MVT::i32);
14849     else
14850       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14851
14852     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14853
14854     if (CondOpcode == ISD::UMULO)
14855       Cond = X86Op.getValue(2);
14856     else
14857       Cond = X86Op.getValue(1);
14858
14859     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14860     addTest = false;
14861   }
14862
14863   if (addTest) {
14864     // Look past the truncate if the high bits are known zero.
14865     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14866       Cond = Cond.getOperand(0);
14867
14868     // We know the result of AND is compared against zero. Try to match
14869     // it to BT.
14870     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14871       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
14872         CC = NewSetCC.getOperand(0);
14873         Cond = NewSetCC.getOperand(1);
14874         addTest = false;
14875       }
14876     }
14877   }
14878
14879   if (addTest) {
14880     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14881     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14882   }
14883
14884   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14885   // a <  b ?  0 : -1 -> RES = setcc_carry
14886   // a >= b ? -1 :  0 -> RES = setcc_carry
14887   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14888   if (Cond.getOpcode() == X86ISD::SUB) {
14889     Cond = ConvertCmpIfNecessary(Cond, DAG);
14890     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14891
14892     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14893         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14894       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14895                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14896                                 Cond);
14897       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14898         return DAG.getNOT(DL, Res, Res.getValueType());
14899       return Res;
14900     }
14901   }
14902
14903   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14904   // widen the cmov and push the truncate through. This avoids introducing a new
14905   // branch during isel and doesn't add any extensions.
14906   if (Op.getValueType() == MVT::i8 &&
14907       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14908     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14909     if (T1.getValueType() == T2.getValueType() &&
14910         // Blacklist CopyFromReg to avoid partial register stalls.
14911         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14912       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14913       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14914       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14915     }
14916   }
14917
14918   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14919   // condition is true.
14920   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14921   SDValue Ops[] = { Op2, Op1, CC, Cond };
14922   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14923 }
14924
14925 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14926                                        const X86Subtarget *Subtarget,
14927                                        SelectionDAG &DAG) {
14928   MVT VT = Op->getSimpleValueType(0);
14929   SDValue In = Op->getOperand(0);
14930   MVT InVT = In.getSimpleValueType();
14931   MVT VTElt = VT.getVectorElementType();
14932   MVT InVTElt = InVT.getVectorElementType();
14933   SDLoc dl(Op);
14934
14935   // SKX processor
14936   if ((InVTElt == MVT::i1) &&
14937       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14938         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14939
14940        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14941         VTElt.getSizeInBits() <= 16)) ||
14942
14943        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14944         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14945
14946        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14947         VTElt.getSizeInBits() >= 32))))
14948     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14949
14950   unsigned int NumElts = VT.getVectorNumElements();
14951
14952   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14953     return SDValue();
14954
14955   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14956     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14957       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14958     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14959   }
14960
14961   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14962   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14963   SDValue NegOne =
14964    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14965                    ExtVT);
14966   SDValue Zero =
14967    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14968
14969   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14970   if (VT.is512BitVector())
14971     return V;
14972   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14973 }
14974
14975 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14976                                              const X86Subtarget *Subtarget,
14977                                              SelectionDAG &DAG) {
14978   SDValue In = Op->getOperand(0);
14979   MVT VT = Op->getSimpleValueType(0);
14980   MVT InVT = In.getSimpleValueType();
14981   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14982
14983   MVT InSVT = InVT.getVectorElementType();
14984   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
14985
14986   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14987     return SDValue();
14988   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14989     return SDValue();
14990
14991   SDLoc dl(Op);
14992
14993   // SSE41 targets can use the pmovsx* instructions directly.
14994   if (Subtarget->hasSSE41())
14995     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14996
14997   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14998   SDValue Curr = In;
14999   MVT CurrVT = InVT;
15000
15001   // As SRAI is only available on i16/i32 types, we expand only up to i32
15002   // and handle i64 separately.
15003   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15004     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15005     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15006     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15007     Curr = DAG.getBitcast(CurrVT, Curr);
15008   }
15009
15010   SDValue SignExt = Curr;
15011   if (CurrVT != InVT) {
15012     unsigned SignExtShift =
15013         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15014     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15015                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15016   }
15017
15018   if (CurrVT == VT)
15019     return SignExt;
15020
15021   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15022     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15023                                DAG.getConstant(31, dl, MVT::i8));
15024     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15025     return DAG.getBitcast(VT, Ext);
15026   }
15027
15028   return SDValue();
15029 }
15030
15031 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15032                                 SelectionDAG &DAG) {
15033   MVT VT = Op->getSimpleValueType(0);
15034   SDValue In = Op->getOperand(0);
15035   MVT InVT = In.getSimpleValueType();
15036   SDLoc dl(Op);
15037
15038   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15039     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15040
15041   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15042       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15043       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15044     return SDValue();
15045
15046   if (Subtarget->hasInt256())
15047     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15048
15049   // Optimize vectors in AVX mode
15050   // Sign extend  v8i16 to v8i32 and
15051   //              v4i32 to v4i64
15052   //
15053   // Divide input vector into two parts
15054   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15055   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15056   // concat the vectors to original VT
15057
15058   unsigned NumElems = InVT.getVectorNumElements();
15059   SDValue Undef = DAG.getUNDEF(InVT);
15060
15061   SmallVector<int,8> ShufMask1(NumElems, -1);
15062   for (unsigned i = 0; i != NumElems/2; ++i)
15063     ShufMask1[i] = i;
15064
15065   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15066
15067   SmallVector<int,8> ShufMask2(NumElems, -1);
15068   for (unsigned i = 0; i != NumElems/2; ++i)
15069     ShufMask2[i] = i + NumElems/2;
15070
15071   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15072
15073   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15074                                 VT.getVectorNumElements()/2);
15075
15076   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15077   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15078
15079   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15080 }
15081
15082 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15083 // may emit an illegal shuffle but the expansion is still better than scalar
15084 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15085 // we'll emit a shuffle and a arithmetic shift.
15086 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15087 // TODO: It is possible to support ZExt by zeroing the undef values during
15088 // the shuffle phase or after the shuffle.
15089 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15090                                  SelectionDAG &DAG) {
15091   MVT RegVT = Op.getSimpleValueType();
15092   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15093   assert(RegVT.isInteger() &&
15094          "We only custom lower integer vector sext loads.");
15095
15096   // Nothing useful we can do without SSE2 shuffles.
15097   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15098
15099   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15100   SDLoc dl(Ld);
15101   EVT MemVT = Ld->getMemoryVT();
15102   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15103   unsigned RegSz = RegVT.getSizeInBits();
15104
15105   ISD::LoadExtType Ext = Ld->getExtensionType();
15106
15107   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15108          && "Only anyext and sext are currently implemented.");
15109   assert(MemVT != RegVT && "Cannot extend to the same type");
15110   assert(MemVT.isVector() && "Must load a vector from memory");
15111
15112   unsigned NumElems = RegVT.getVectorNumElements();
15113   unsigned MemSz = MemVT.getSizeInBits();
15114   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15115
15116   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15117     // The only way in which we have a legal 256-bit vector result but not the
15118     // integer 256-bit operations needed to directly lower a sextload is if we
15119     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15120     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15121     // correctly legalized. We do this late to allow the canonical form of
15122     // sextload to persist throughout the rest of the DAG combiner -- it wants
15123     // to fold together any extensions it can, and so will fuse a sign_extend
15124     // of an sextload into a sextload targeting a wider value.
15125     SDValue Load;
15126     if (MemSz == 128) {
15127       // Just switch this to a normal load.
15128       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15129                                        "it must be a legal 128-bit vector "
15130                                        "type!");
15131       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15132                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15133                   Ld->isInvariant(), Ld->getAlignment());
15134     } else {
15135       assert(MemSz < 128 &&
15136              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15137       // Do an sext load to a 128-bit vector type. We want to use the same
15138       // number of elements, but elements half as wide. This will end up being
15139       // recursively lowered by this routine, but will succeed as we definitely
15140       // have all the necessary features if we're using AVX1.
15141       EVT HalfEltVT =
15142           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15143       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15144       Load =
15145           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15146                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15147                          Ld->isNonTemporal(), Ld->isInvariant(),
15148                          Ld->getAlignment());
15149     }
15150
15151     // Replace chain users with the new chain.
15152     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15153     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15154
15155     // Finally, do a normal sign-extend to the desired register.
15156     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15157   }
15158
15159   // All sizes must be a power of two.
15160   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15161          "Non-power-of-two elements are not custom lowered!");
15162
15163   // Attempt to load the original value using scalar loads.
15164   // Find the largest scalar type that divides the total loaded size.
15165   MVT SclrLoadTy = MVT::i8;
15166   for (MVT Tp : MVT::integer_valuetypes()) {
15167     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15168       SclrLoadTy = Tp;
15169     }
15170   }
15171
15172   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15173   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15174       (64 <= MemSz))
15175     SclrLoadTy = MVT::f64;
15176
15177   // Calculate the number of scalar loads that we need to perform
15178   // in order to load our vector from memory.
15179   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15180
15181   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15182          "Can only lower sext loads with a single scalar load!");
15183
15184   unsigned loadRegZize = RegSz;
15185   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15186     loadRegZize = 128;
15187
15188   // Represent our vector as a sequence of elements which are the
15189   // largest scalar that we can load.
15190   EVT LoadUnitVecVT = EVT::getVectorVT(
15191       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15192
15193   // Represent the data using the same element type that is stored in
15194   // memory. In practice, we ''widen'' MemVT.
15195   EVT WideVecVT =
15196       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15197                        loadRegZize / MemVT.getScalarSizeInBits());
15198
15199   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15200          "Invalid vector type");
15201
15202   // We can't shuffle using an illegal type.
15203   assert(TLI.isTypeLegal(WideVecVT) &&
15204          "We only lower types that form legal widened vector types");
15205
15206   SmallVector<SDValue, 8> Chains;
15207   SDValue Ptr = Ld->getBasePtr();
15208   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15209                                       TLI.getPointerTy(DAG.getDataLayout()));
15210   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15211
15212   for (unsigned i = 0; i < NumLoads; ++i) {
15213     // Perform a single load.
15214     SDValue ScalarLoad =
15215         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15216                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15217                     Ld->getAlignment());
15218     Chains.push_back(ScalarLoad.getValue(1));
15219     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15220     // another round of DAGCombining.
15221     if (i == 0)
15222       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15223     else
15224       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15225                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15226
15227     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15228   }
15229
15230   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15231
15232   // Bitcast the loaded value to a vector of the original element type, in
15233   // the size of the target vector type.
15234   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15235   unsigned SizeRatio = RegSz / MemSz;
15236
15237   if (Ext == ISD::SEXTLOAD) {
15238     // If we have SSE4.1, we can directly emit a VSEXT node.
15239     if (Subtarget->hasSSE41()) {
15240       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15241       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15242       return Sext;
15243     }
15244
15245     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15246     // lanes.
15247     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15248            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15249
15250     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15251     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15252     return Shuff;
15253   }
15254
15255   // Redistribute the loaded elements into the different locations.
15256   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15257   for (unsigned i = 0; i != NumElems; ++i)
15258     ShuffleVec[i * SizeRatio] = i;
15259
15260   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15261                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15262
15263   // Bitcast to the requested type.
15264   Shuff = DAG.getBitcast(RegVT, Shuff);
15265   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15266   return Shuff;
15267 }
15268
15269 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15270 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15271 // from the AND / OR.
15272 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15273   Opc = Op.getOpcode();
15274   if (Opc != ISD::OR && Opc != ISD::AND)
15275     return false;
15276   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15277           Op.getOperand(0).hasOneUse() &&
15278           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15279           Op.getOperand(1).hasOneUse());
15280 }
15281
15282 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15283 // 1 and that the SETCC node has a single use.
15284 static bool isXor1OfSetCC(SDValue Op) {
15285   if (Op.getOpcode() != ISD::XOR)
15286     return false;
15287   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15288   if (N1C && N1C->getAPIntValue() == 1) {
15289     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15290       Op.getOperand(0).hasOneUse();
15291   }
15292   return false;
15293 }
15294
15295 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15296   bool addTest = true;
15297   SDValue Chain = Op.getOperand(0);
15298   SDValue Cond  = Op.getOperand(1);
15299   SDValue Dest  = Op.getOperand(2);
15300   SDLoc dl(Op);
15301   SDValue CC;
15302   bool Inverted = false;
15303
15304   if (Cond.getOpcode() == ISD::SETCC) {
15305     // Check for setcc([su]{add,sub,mul}o == 0).
15306     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15307         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15308         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15309         Cond.getOperand(0).getResNo() == 1 &&
15310         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15311          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15312          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15313          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15314          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15315          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15316       Inverted = true;
15317       Cond = Cond.getOperand(0);
15318     } else {
15319       SDValue NewCond = LowerSETCC(Cond, DAG);
15320       if (NewCond.getNode())
15321         Cond = NewCond;
15322     }
15323   }
15324 #if 0
15325   // FIXME: LowerXALUO doesn't handle these!!
15326   else if (Cond.getOpcode() == X86ISD::ADD  ||
15327            Cond.getOpcode() == X86ISD::SUB  ||
15328            Cond.getOpcode() == X86ISD::SMUL ||
15329            Cond.getOpcode() == X86ISD::UMUL)
15330     Cond = LowerXALUO(Cond, DAG);
15331 #endif
15332
15333   // Look pass (and (setcc_carry (cmp ...)), 1).
15334   if (Cond.getOpcode() == ISD::AND &&
15335       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15336     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15337     if (C && C->getAPIntValue() == 1)
15338       Cond = Cond.getOperand(0);
15339   }
15340
15341   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15342   // setting operand in place of the X86ISD::SETCC.
15343   unsigned CondOpcode = Cond.getOpcode();
15344   if (CondOpcode == X86ISD::SETCC ||
15345       CondOpcode == X86ISD::SETCC_CARRY) {
15346     CC = Cond.getOperand(0);
15347
15348     SDValue Cmp = Cond.getOperand(1);
15349     unsigned Opc = Cmp.getOpcode();
15350     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15351     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15352       Cond = Cmp;
15353       addTest = false;
15354     } else {
15355       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15356       default: break;
15357       case X86::COND_O:
15358       case X86::COND_B:
15359         // These can only come from an arithmetic instruction with overflow,
15360         // e.g. SADDO, UADDO.
15361         Cond = Cond.getNode()->getOperand(1);
15362         addTest = false;
15363         break;
15364       }
15365     }
15366   }
15367   CondOpcode = Cond.getOpcode();
15368   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15369       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15370       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15371        Cond.getOperand(0).getValueType() != MVT::i8)) {
15372     SDValue LHS = Cond.getOperand(0);
15373     SDValue RHS = Cond.getOperand(1);
15374     unsigned X86Opcode;
15375     unsigned X86Cond;
15376     SDVTList VTs;
15377     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15378     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15379     // X86ISD::INC).
15380     switch (CondOpcode) {
15381     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15382     case ISD::SADDO:
15383       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15384         if (C->isOne()) {
15385           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15386           break;
15387         }
15388       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15389     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15390     case ISD::SSUBO:
15391       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15392         if (C->isOne()) {
15393           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15394           break;
15395         }
15396       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15397     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15398     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15399     default: llvm_unreachable("unexpected overflowing operator");
15400     }
15401     if (Inverted)
15402       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15403     if (CondOpcode == ISD::UMULO)
15404       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15405                           MVT::i32);
15406     else
15407       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15408
15409     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15410
15411     if (CondOpcode == ISD::UMULO)
15412       Cond = X86Op.getValue(2);
15413     else
15414       Cond = X86Op.getValue(1);
15415
15416     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15417     addTest = false;
15418   } else {
15419     unsigned CondOpc;
15420     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15421       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15422       if (CondOpc == ISD::OR) {
15423         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15424         // two branches instead of an explicit OR instruction with a
15425         // separate test.
15426         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15427             isX86LogicalCmp(Cmp)) {
15428           CC = Cond.getOperand(0).getOperand(0);
15429           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15430                               Chain, Dest, CC, Cmp);
15431           CC = Cond.getOperand(1).getOperand(0);
15432           Cond = Cmp;
15433           addTest = false;
15434         }
15435       } else { // ISD::AND
15436         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15437         // two branches instead of an explicit AND instruction with a
15438         // separate test. However, we only do this if this block doesn't
15439         // have a fall-through edge, because this requires an explicit
15440         // jmp when the condition is false.
15441         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15442             isX86LogicalCmp(Cmp) &&
15443             Op.getNode()->hasOneUse()) {
15444           X86::CondCode CCode =
15445             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15446           CCode = X86::GetOppositeBranchCondition(CCode);
15447           CC = DAG.getConstant(CCode, dl, MVT::i8);
15448           SDNode *User = *Op.getNode()->use_begin();
15449           // Look for an unconditional branch following this conditional branch.
15450           // We need this because we need to reverse the successors in order
15451           // to implement FCMP_OEQ.
15452           if (User->getOpcode() == ISD::BR) {
15453             SDValue FalseBB = User->getOperand(1);
15454             SDNode *NewBR =
15455               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15456             assert(NewBR == User);
15457             (void)NewBR;
15458             Dest = FalseBB;
15459
15460             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15461                                 Chain, Dest, CC, Cmp);
15462             X86::CondCode CCode =
15463               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15464             CCode = X86::GetOppositeBranchCondition(CCode);
15465             CC = DAG.getConstant(CCode, dl, MVT::i8);
15466             Cond = Cmp;
15467             addTest = false;
15468           }
15469         }
15470       }
15471     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15472       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15473       // It should be transformed during dag combiner except when the condition
15474       // is set by a arithmetics with overflow node.
15475       X86::CondCode CCode =
15476         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15477       CCode = X86::GetOppositeBranchCondition(CCode);
15478       CC = DAG.getConstant(CCode, dl, MVT::i8);
15479       Cond = Cond.getOperand(0).getOperand(1);
15480       addTest = false;
15481     } else if (Cond.getOpcode() == ISD::SETCC &&
15482                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15483       // For FCMP_OEQ, we can emit
15484       // two branches instead of an explicit AND instruction with a
15485       // separate test. However, we only do this if this block doesn't
15486       // have a fall-through edge, because this requires an explicit
15487       // jmp when the condition is false.
15488       if (Op.getNode()->hasOneUse()) {
15489         SDNode *User = *Op.getNode()->use_begin();
15490         // Look for an unconditional branch following this conditional branch.
15491         // We need this because we need to reverse the successors in order
15492         // to implement FCMP_OEQ.
15493         if (User->getOpcode() == ISD::BR) {
15494           SDValue FalseBB = User->getOperand(1);
15495           SDNode *NewBR =
15496             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15497           assert(NewBR == User);
15498           (void)NewBR;
15499           Dest = FalseBB;
15500
15501           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15502                                     Cond.getOperand(0), Cond.getOperand(1));
15503           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15504           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15505           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15506                               Chain, Dest, CC, Cmp);
15507           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15508           Cond = Cmp;
15509           addTest = false;
15510         }
15511       }
15512     } else if (Cond.getOpcode() == ISD::SETCC &&
15513                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15514       // For FCMP_UNE, we can emit
15515       // two branches instead of an explicit AND instruction with a
15516       // separate test. However, we only do this if this block doesn't
15517       // have a fall-through edge, because this requires an explicit
15518       // jmp when the condition is false.
15519       if (Op.getNode()->hasOneUse()) {
15520         SDNode *User = *Op.getNode()->use_begin();
15521         // Look for an unconditional branch following this conditional branch.
15522         // We need this because we need to reverse the successors in order
15523         // to implement FCMP_UNE.
15524         if (User->getOpcode() == ISD::BR) {
15525           SDValue FalseBB = User->getOperand(1);
15526           SDNode *NewBR =
15527             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15528           assert(NewBR == User);
15529           (void)NewBR;
15530
15531           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15532                                     Cond.getOperand(0), Cond.getOperand(1));
15533           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15534           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15535           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15536                               Chain, Dest, CC, Cmp);
15537           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15538           Cond = Cmp;
15539           addTest = false;
15540           Dest = FalseBB;
15541         }
15542       }
15543     }
15544   }
15545
15546   if (addTest) {
15547     // Look pass the truncate if the high bits are known zero.
15548     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15549         Cond = Cond.getOperand(0);
15550
15551     // We know the result of AND is compared against zero. Try to match
15552     // it to BT.
15553     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15554       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15555         CC = NewSetCC.getOperand(0);
15556         Cond = NewSetCC.getOperand(1);
15557         addTest = false;
15558       }
15559     }
15560   }
15561
15562   if (addTest) {
15563     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15564     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15565     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15566   }
15567   Cond = ConvertCmpIfNecessary(Cond, DAG);
15568   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15569                      Chain, Dest, CC, Cond);
15570 }
15571
15572 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15573 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15574 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15575 // that the guard pages used by the OS virtual memory manager are allocated in
15576 // correct sequence.
15577 SDValue
15578 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15579                                            SelectionDAG &DAG) const {
15580   MachineFunction &MF = DAG.getMachineFunction();
15581   bool SplitStack = MF.shouldSplitStack();
15582   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15583                SplitStack;
15584   SDLoc dl(Op);
15585
15586   if (!Lower) {
15587     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15588     SDNode* Node = Op.getNode();
15589
15590     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15591     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15592         " not tell us which reg is the stack pointer!");
15593     EVT VT = Node->getValueType(0);
15594     SDValue Tmp1 = SDValue(Node, 0);
15595     SDValue Tmp2 = SDValue(Node, 1);
15596     SDValue Tmp3 = Node->getOperand(2);
15597     SDValue Chain = Tmp1.getOperand(0);
15598
15599     // Chain the dynamic stack allocation so that it doesn't modify the stack
15600     // pointer when other instructions are using the stack.
15601     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15602         SDLoc(Node));
15603
15604     SDValue Size = Tmp2.getOperand(1);
15605     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15606     Chain = SP.getValue(1);
15607     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15608     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15609     unsigned StackAlign = TFI.getStackAlignment();
15610     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15611     if (Align > StackAlign)
15612       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15613           DAG.getConstant(-(uint64_t)Align, dl, VT));
15614     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15615
15616     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15617         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15618         SDLoc(Node));
15619
15620     SDValue Ops[2] = { Tmp1, Tmp2 };
15621     return DAG.getMergeValues(Ops, dl);
15622   }
15623
15624   // Get the inputs.
15625   SDValue Chain = Op.getOperand(0);
15626   SDValue Size  = Op.getOperand(1);
15627   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15628   EVT VT = Op.getNode()->getValueType(0);
15629
15630   bool Is64Bit = Subtarget->is64Bit();
15631   MVT SPTy = getPointerTy(DAG.getDataLayout());
15632
15633   if (SplitStack) {
15634     MachineRegisterInfo &MRI = MF.getRegInfo();
15635
15636     if (Is64Bit) {
15637       // The 64 bit implementation of segmented stacks needs to clobber both r10
15638       // r11. This makes it impossible to use it along with nested parameters.
15639       const Function *F = MF.getFunction();
15640
15641       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15642            I != E; ++I)
15643         if (I->hasNestAttr())
15644           report_fatal_error("Cannot use segmented stacks with functions that "
15645                              "have nested arguments.");
15646     }
15647
15648     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15649     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15650     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15651     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15652                                 DAG.getRegister(Vreg, SPTy));
15653     SDValue Ops1[2] = { Value, Chain };
15654     return DAG.getMergeValues(Ops1, dl);
15655   } else {
15656     SDValue Flag;
15657     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15658
15659     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15660     Flag = Chain.getValue(1);
15661     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15662
15663     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15664
15665     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15666     unsigned SPReg = RegInfo->getStackRegister();
15667     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15668     Chain = SP.getValue(1);
15669
15670     if (Align) {
15671       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15672                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15673       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15674     }
15675
15676     SDValue Ops1[2] = { SP, Chain };
15677     return DAG.getMergeValues(Ops1, dl);
15678   }
15679 }
15680
15681 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15682   MachineFunction &MF = DAG.getMachineFunction();
15683   auto PtrVT = getPointerTy(MF.getDataLayout());
15684   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15685
15686   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15687   SDLoc DL(Op);
15688
15689   if (!Subtarget->is64Bit() ||
15690       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15691     // vastart just stores the address of the VarArgsFrameIndex slot into the
15692     // memory location argument.
15693     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15694     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15695                         MachinePointerInfo(SV), false, false, 0);
15696   }
15697
15698   // __va_list_tag:
15699   //   gp_offset         (0 - 6 * 8)
15700   //   fp_offset         (48 - 48 + 8 * 16)
15701   //   overflow_arg_area (point to parameters coming in memory).
15702   //   reg_save_area
15703   SmallVector<SDValue, 8> MemOps;
15704   SDValue FIN = Op.getOperand(1);
15705   // Store gp_offset
15706   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15707                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15708                                                DL, MVT::i32),
15709                                FIN, MachinePointerInfo(SV), false, false, 0);
15710   MemOps.push_back(Store);
15711
15712   // Store fp_offset
15713   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15714   Store = DAG.getStore(Op.getOperand(0), DL,
15715                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15716                                        MVT::i32),
15717                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15718   MemOps.push_back(Store);
15719
15720   // Store ptr to overflow_arg_area
15721   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15722   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15723   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15724                        MachinePointerInfo(SV, 8),
15725                        false, false, 0);
15726   MemOps.push_back(Store);
15727
15728   // Store ptr to reg_save_area.
15729   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15730       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15731   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15732   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15733       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15734   MemOps.push_back(Store);
15735   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15736 }
15737
15738 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15739   assert(Subtarget->is64Bit() &&
15740          "LowerVAARG only handles 64-bit va_arg!");
15741   assert(Op.getNode()->getNumOperands() == 4);
15742
15743   MachineFunction &MF = DAG.getMachineFunction();
15744   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15745     // The Win64 ABI uses char* instead of a structure.
15746     return DAG.expandVAArg(Op.getNode());
15747
15748   SDValue Chain = Op.getOperand(0);
15749   SDValue SrcPtr = Op.getOperand(1);
15750   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15751   unsigned Align = Op.getConstantOperandVal(3);
15752   SDLoc dl(Op);
15753
15754   EVT ArgVT = Op.getNode()->getValueType(0);
15755   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15756   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15757   uint8_t ArgMode;
15758
15759   // Decide which area this value should be read from.
15760   // TODO: Implement the AMD64 ABI in its entirety. This simple
15761   // selection mechanism works only for the basic types.
15762   if (ArgVT == MVT::f80) {
15763     llvm_unreachable("va_arg for f80 not yet implemented");
15764   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15765     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15766   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15767     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15768   } else {
15769     llvm_unreachable("Unhandled argument type in LowerVAARG");
15770   }
15771
15772   if (ArgMode == 2) {
15773     // Sanity Check: Make sure using fp_offset makes sense.
15774     assert(!Subtarget->useSoftFloat() &&
15775            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15776            Subtarget->hasSSE1());
15777   }
15778
15779   // Insert VAARG_64 node into the DAG
15780   // VAARG_64 returns two values: Variable Argument Address, Chain
15781   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15782                        DAG.getConstant(ArgMode, dl, MVT::i8),
15783                        DAG.getConstant(Align, dl, MVT::i32)};
15784   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15785   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15786                                           VTs, InstOps, MVT::i64,
15787                                           MachinePointerInfo(SV),
15788                                           /*Align=*/0,
15789                                           /*Volatile=*/false,
15790                                           /*ReadMem=*/true,
15791                                           /*WriteMem=*/true);
15792   Chain = VAARG.getValue(1);
15793
15794   // Load the next argument and return it
15795   return DAG.getLoad(ArgVT, dl,
15796                      Chain,
15797                      VAARG,
15798                      MachinePointerInfo(),
15799                      false, false, false, 0);
15800 }
15801
15802 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15803                            SelectionDAG &DAG) {
15804   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15805   // where a va_list is still an i8*.
15806   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15807   if (Subtarget->isCallingConvWin64(
15808         DAG.getMachineFunction().getFunction()->getCallingConv()))
15809     // Probably a Win64 va_copy.
15810     return DAG.expandVACopy(Op.getNode());
15811
15812   SDValue Chain = Op.getOperand(0);
15813   SDValue DstPtr = Op.getOperand(1);
15814   SDValue SrcPtr = Op.getOperand(2);
15815   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15816   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15817   SDLoc DL(Op);
15818
15819   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15820                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15821                        false, false,
15822                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15823 }
15824
15825 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15826 // amount is a constant. Takes immediate version of shift as input.
15827 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15828                                           SDValue SrcOp, uint64_t ShiftAmt,
15829                                           SelectionDAG &DAG) {
15830   MVT ElementType = VT.getVectorElementType();
15831
15832   // Fold this packed shift into its first operand if ShiftAmt is 0.
15833   if (ShiftAmt == 0)
15834     return SrcOp;
15835
15836   // Check for ShiftAmt >= element width
15837   if (ShiftAmt >= ElementType.getSizeInBits()) {
15838     if (Opc == X86ISD::VSRAI)
15839       ShiftAmt = ElementType.getSizeInBits() - 1;
15840     else
15841       return DAG.getConstant(0, dl, VT);
15842   }
15843
15844   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15845          && "Unknown target vector shift-by-constant node");
15846
15847   // Fold this packed vector shift into a build vector if SrcOp is a
15848   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15849   if (VT == SrcOp.getSimpleValueType() &&
15850       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15851     SmallVector<SDValue, 8> Elts;
15852     unsigned NumElts = SrcOp->getNumOperands();
15853     ConstantSDNode *ND;
15854
15855     switch(Opc) {
15856     default: llvm_unreachable(nullptr);
15857     case X86ISD::VSHLI:
15858       for (unsigned i=0; i!=NumElts; ++i) {
15859         SDValue CurrentOp = SrcOp->getOperand(i);
15860         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15861           Elts.push_back(CurrentOp);
15862           continue;
15863         }
15864         ND = cast<ConstantSDNode>(CurrentOp);
15865         const APInt &C = ND->getAPIntValue();
15866         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15867       }
15868       break;
15869     case X86ISD::VSRLI:
15870       for (unsigned i=0; i!=NumElts; ++i) {
15871         SDValue CurrentOp = SrcOp->getOperand(i);
15872         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15873           Elts.push_back(CurrentOp);
15874           continue;
15875         }
15876         ND = cast<ConstantSDNode>(CurrentOp);
15877         const APInt &C = ND->getAPIntValue();
15878         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15879       }
15880       break;
15881     case X86ISD::VSRAI:
15882       for (unsigned i=0; i!=NumElts; ++i) {
15883         SDValue CurrentOp = SrcOp->getOperand(i);
15884         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15885           Elts.push_back(CurrentOp);
15886           continue;
15887         }
15888         ND = cast<ConstantSDNode>(CurrentOp);
15889         const APInt &C = ND->getAPIntValue();
15890         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15891       }
15892       break;
15893     }
15894
15895     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15896   }
15897
15898   return DAG.getNode(Opc, dl, VT, SrcOp,
15899                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15900 }
15901
15902 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15903 // may or may not be a constant. Takes immediate version of shift as input.
15904 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15905                                    SDValue SrcOp, SDValue ShAmt,
15906                                    SelectionDAG &DAG) {
15907   MVT SVT = ShAmt.getSimpleValueType();
15908   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15909
15910   // Catch shift-by-constant.
15911   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15912     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15913                                       CShAmt->getZExtValue(), DAG);
15914
15915   // Change opcode to non-immediate version
15916   switch (Opc) {
15917     default: llvm_unreachable("Unknown target vector shift node");
15918     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15919     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15920     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15921   }
15922
15923   const X86Subtarget &Subtarget =
15924       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15925   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15926       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15927     // Let the shuffle legalizer expand this shift amount node.
15928     SDValue Op0 = ShAmt.getOperand(0);
15929     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15930     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15931   } else {
15932     // Need to build a vector containing shift amount.
15933     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15934     SmallVector<SDValue, 4> ShOps;
15935     ShOps.push_back(ShAmt);
15936     if (SVT == MVT::i32) {
15937       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15938       ShOps.push_back(DAG.getUNDEF(SVT));
15939     }
15940     ShOps.push_back(DAG.getUNDEF(SVT));
15941
15942     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15943     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15944   }
15945
15946   // The return type has to be a 128-bit type with the same element
15947   // type as the input type.
15948   MVT EltVT = VT.getVectorElementType();
15949   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15950
15951   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15952   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15953 }
15954
15955 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15956 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15957 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15958 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15959                                     SDValue PreservedSrc,
15960                                     const X86Subtarget *Subtarget,
15961                                     SelectionDAG &DAG) {
15962     MVT VT = Op.getSimpleValueType();
15963     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
15964     SDValue VMask;
15965     unsigned OpcodeSelect = ISD::VSELECT;
15966     SDLoc dl(Op);
15967
15968     if (isAllOnes(Mask))
15969       return Op;
15970
15971     if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
15972       MVT newMaskVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
15973       VMask = DAG.getBitcast(MaskVT,
15974                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15975     } else {
15976       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
15977                                        Mask.getSimpleValueType().getSizeInBits());
15978       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15979       // are extracted by EXTRACT_SUBVECTOR.
15980       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15981                           DAG.getBitcast(BitcastVT, Mask),
15982                           DAG.getIntPtrConstant(0, dl));
15983     }
15984
15985     switch (Op.getOpcode()) {
15986     default: break;
15987     case X86ISD::PCMPEQM:
15988     case X86ISD::PCMPGTM:
15989     case X86ISD::CMPM:
15990     case X86ISD::CMPMU:
15991       return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15992     case X86ISD::VFPCLASS:
15993       return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15994     case X86ISD::VTRUNC:
15995     case X86ISD::VTRUNCS:
15996     case X86ISD::VTRUNCUS:
15997       // We can't use ISD::VSELECT here because it is not always "Legal"
15998       // for the destination type. For example vpmovqb require only AVX512
15999       // and vselect that can operate on byte element type require BWI
16000       OpcodeSelect = X86ISD::SELECT;
16001       break;
16002     }
16003     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16004       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16005     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16006 }
16007
16008 /// \brief Creates an SDNode for a predicated scalar operation.
16009 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16010 /// The mask is coming as MVT::i8 and it should be truncated
16011 /// to MVT::i1 while lowering masking intrinsics.
16012 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16013 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16014 /// for a scalar instruction.
16015 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16016                                     SDValue PreservedSrc,
16017                                     const X86Subtarget *Subtarget,
16018                                     SelectionDAG &DAG) {
16019   if (isAllOnes(Mask))
16020     return Op;
16021
16022   MVT VT = Op.getSimpleValueType();
16023   SDLoc dl(Op);
16024   // The mask should be of type MVT::i1
16025   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16026
16027   if (Op.getOpcode() == X86ISD::FSETCC)
16028     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16029   if (Op.getOpcode() == X86ISD::VFPCLASS)
16030     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16031
16032   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16033     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16034   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16035 }
16036
16037 static int getSEHRegistrationNodeSize(const Function *Fn) {
16038   if (!Fn->hasPersonalityFn())
16039     report_fatal_error(
16040         "querying registration node size for function without personality");
16041   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16042   // WinEHStatePass for the full struct definition.
16043   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16044   case EHPersonality::MSVC_X86SEH: return 24;
16045   case EHPersonality::MSVC_CXX: return 16;
16046   default: break;
16047   }
16048   report_fatal_error("can only recover FP for MSVC EH personality functions");
16049 }
16050
16051 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16052 /// function or when returning to a parent frame after catching an exception, we
16053 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16054 /// Here's the math:
16055 ///   RegNodeBase = EntryEBP - RegNodeSize
16056 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
16057 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16058 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16059 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16060                                    SDValue EntryEBP) {
16061   MachineFunction &MF = DAG.getMachineFunction();
16062   SDLoc dl;
16063
16064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16065   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16066
16067   // It's possible that the parent function no longer has a personality function
16068   // if the exceptional code was optimized away, in which case we just return
16069   // the incoming EBP.
16070   if (!Fn->hasPersonalityFn())
16071     return EntryEBP;
16072
16073   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16074
16075   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16076   // registration.
16077   MCSymbol *OffsetSym =
16078       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16079           GlobalValue::getRealLinkageName(Fn->getName()));
16080   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16081   SDValue RegNodeFrameOffset =
16082       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16083
16084   // RegNodeBase = EntryEBP - RegNodeSize
16085   // ParentFP = RegNodeBase - RegNodeFrameOffset
16086   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16087                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16088   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16089 }
16090
16091 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16092                                        SelectionDAG &DAG) {
16093   SDLoc dl(Op);
16094   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16095   MVT VT = Op.getSimpleValueType();
16096   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16097   if (IntrData) {
16098     switch(IntrData->Type) {
16099     case INTR_TYPE_1OP:
16100       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16101     case INTR_TYPE_2OP:
16102       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16103         Op.getOperand(2));
16104     case INTR_TYPE_2OP_IMM8:
16105       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16106                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16107     case INTR_TYPE_3OP:
16108       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16109         Op.getOperand(2), Op.getOperand(3));
16110     case INTR_TYPE_4OP:
16111       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16112         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16113     case INTR_TYPE_1OP_MASK_RM: {
16114       SDValue Src = Op.getOperand(1);
16115       SDValue PassThru = Op.getOperand(2);
16116       SDValue Mask = Op.getOperand(3);
16117       SDValue RoundingMode;
16118       // We allways add rounding mode to the Node.
16119       // If the rounding mode is not specified, we add the
16120       // "current direction" mode.
16121       if (Op.getNumOperands() == 4)
16122         RoundingMode =
16123           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16124       else
16125         RoundingMode = Op.getOperand(4);
16126       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16127       if (IntrWithRoundingModeOpcode != 0)
16128         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16129             X86::STATIC_ROUNDING::CUR_DIRECTION)
16130           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16131                                       dl, Op.getValueType(), Src, RoundingMode),
16132                                       Mask, PassThru, Subtarget, DAG);
16133       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16134                                               RoundingMode),
16135                                   Mask, PassThru, Subtarget, DAG);
16136     }
16137     case INTR_TYPE_1OP_MASK: {
16138       SDValue Src = Op.getOperand(1);
16139       SDValue PassThru = Op.getOperand(2);
16140       SDValue Mask = Op.getOperand(3);
16141       // We add rounding mode to the Node when
16142       //   - RM Opcode is specified and
16143       //   - RM is not "current direction".
16144       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16145       if (IntrWithRoundingModeOpcode != 0) {
16146         SDValue Rnd = Op.getOperand(4);
16147         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16148         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16149           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16150                                       dl, Op.getValueType(),
16151                                       Src, Rnd),
16152                                       Mask, PassThru, Subtarget, DAG);
16153         }
16154       }
16155       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16156                                   Mask, PassThru, Subtarget, DAG);
16157     }
16158     case INTR_TYPE_SCALAR_MASK: {
16159       SDValue Src1 = Op.getOperand(1);
16160       SDValue Src2 = Op.getOperand(2);
16161       SDValue passThru = Op.getOperand(3);
16162       SDValue Mask = Op.getOperand(4);
16163       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16164                                   Mask, passThru, Subtarget, DAG);
16165     }
16166     case INTR_TYPE_SCALAR_MASK_RM: {
16167       SDValue Src1 = Op.getOperand(1);
16168       SDValue Src2 = Op.getOperand(2);
16169       SDValue Src0 = Op.getOperand(3);
16170       SDValue Mask = Op.getOperand(4);
16171       // There are 2 kinds of intrinsics in this group:
16172       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16173       // (2) With rounding mode and sae - 7 operands.
16174       if (Op.getNumOperands() == 6) {
16175         SDValue Sae  = Op.getOperand(5);
16176         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16177         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16178                                                 Sae),
16179                                     Mask, Src0, Subtarget, DAG);
16180       }
16181       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16182       SDValue RoundingMode  = Op.getOperand(5);
16183       SDValue Sae  = Op.getOperand(6);
16184       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16185                                               RoundingMode, Sae),
16186                                   Mask, Src0, Subtarget, DAG);
16187     }
16188     case INTR_TYPE_2OP_MASK:
16189     case INTR_TYPE_2OP_IMM8_MASK: {
16190       SDValue Src1 = Op.getOperand(1);
16191       SDValue Src2 = Op.getOperand(2);
16192       SDValue PassThru = Op.getOperand(3);
16193       SDValue Mask = Op.getOperand(4);
16194
16195       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16196         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16197
16198       // We specify 2 possible opcodes for intrinsics with rounding modes.
16199       // First, we check if the intrinsic may have non-default rounding mode,
16200       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16201       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16202       if (IntrWithRoundingModeOpcode != 0) {
16203         SDValue Rnd = Op.getOperand(5);
16204         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16205         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16206           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16207                                       dl, Op.getValueType(),
16208                                       Src1, Src2, Rnd),
16209                                       Mask, PassThru, Subtarget, DAG);
16210         }
16211       }
16212       // TODO: Intrinsics should have fast-math-flags to propagate.
16213       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16214                                   Mask, PassThru, Subtarget, DAG);
16215     }
16216     case INTR_TYPE_2OP_MASK_RM: {
16217       SDValue Src1 = Op.getOperand(1);
16218       SDValue Src2 = Op.getOperand(2);
16219       SDValue PassThru = Op.getOperand(3);
16220       SDValue Mask = Op.getOperand(4);
16221       // We specify 2 possible modes for intrinsics, with/without rounding
16222       // modes.
16223       // First, we check if the intrinsic have rounding mode (6 operands),
16224       // if not, we set rounding mode to "current".
16225       SDValue Rnd;
16226       if (Op.getNumOperands() == 6)
16227         Rnd = Op.getOperand(5);
16228       else
16229         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16230       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16231                                               Src1, Src2, Rnd),
16232                                   Mask, PassThru, Subtarget, DAG);
16233     }
16234     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16235       SDValue Src1 = Op.getOperand(1);
16236       SDValue Src2 = Op.getOperand(2);
16237       SDValue Src3 = Op.getOperand(3);
16238       SDValue PassThru = Op.getOperand(4);
16239       SDValue Mask = Op.getOperand(5);
16240       SDValue Sae  = Op.getOperand(6);
16241
16242       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16243                                               Src2, Src3, Sae),
16244                                   Mask, PassThru, Subtarget, DAG);
16245     }
16246     case INTR_TYPE_3OP_MASK_RM: {
16247       SDValue Src1 = Op.getOperand(1);
16248       SDValue Src2 = Op.getOperand(2);
16249       SDValue Imm = Op.getOperand(3);
16250       SDValue PassThru = Op.getOperand(4);
16251       SDValue Mask = Op.getOperand(5);
16252       // We specify 2 possible modes for intrinsics, with/without rounding
16253       // modes.
16254       // First, we check if the intrinsic have rounding mode (7 operands),
16255       // if not, we set rounding mode to "current".
16256       SDValue Rnd;
16257       if (Op.getNumOperands() == 7)
16258         Rnd = Op.getOperand(6);
16259       else
16260         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16261       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16262         Src1, Src2, Imm, Rnd),
16263         Mask, PassThru, Subtarget, DAG);
16264     }
16265     case INTR_TYPE_3OP_IMM8_MASK:
16266     case INTR_TYPE_3OP_MASK:
16267     case INSERT_SUBVEC: {
16268       SDValue Src1 = Op.getOperand(1);
16269       SDValue Src2 = Op.getOperand(2);
16270       SDValue Src3 = Op.getOperand(3);
16271       SDValue PassThru = Op.getOperand(4);
16272       SDValue Mask = Op.getOperand(5);
16273
16274       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16275         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16276       else if (IntrData->Type == INSERT_SUBVEC) {
16277         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16278         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16279         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16280         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16281         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16282       }
16283
16284       // We specify 2 possible opcodes for intrinsics with rounding modes.
16285       // First, we check if the intrinsic may have non-default rounding mode,
16286       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16287       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16288       if (IntrWithRoundingModeOpcode != 0) {
16289         SDValue Rnd = Op.getOperand(6);
16290         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16291         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16292           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16293                                       dl, Op.getValueType(),
16294                                       Src1, Src2, Src3, Rnd),
16295                                       Mask, PassThru, Subtarget, DAG);
16296         }
16297       }
16298       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16299                                               Src1, Src2, Src3),
16300                                   Mask, PassThru, Subtarget, DAG);
16301     }
16302     case VPERM_3OP_MASKZ:
16303     case VPERM_3OP_MASK:
16304     case FMA_OP_MASK3:
16305     case FMA_OP_MASKZ:
16306     case FMA_OP_MASK: {
16307       SDValue Src1 = Op.getOperand(1);
16308       SDValue Src2 = Op.getOperand(2);
16309       SDValue Src3 = Op.getOperand(3);
16310       SDValue Mask = Op.getOperand(4);
16311       MVT VT = Op.getSimpleValueType();
16312       SDValue PassThru = SDValue();
16313
16314       // set PassThru element
16315       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16316         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16317       else if (IntrData->Type == FMA_OP_MASK3)
16318         PassThru = Src3;
16319       else
16320         PassThru = Src1;
16321
16322       // We specify 2 possible opcodes for intrinsics with rounding modes.
16323       // First, we check if the intrinsic may have non-default rounding mode,
16324       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16325       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16326       if (IntrWithRoundingModeOpcode != 0) {
16327         SDValue Rnd = Op.getOperand(5);
16328         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16329             X86::STATIC_ROUNDING::CUR_DIRECTION)
16330           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16331                                                   dl, Op.getValueType(),
16332                                                   Src1, Src2, Src3, Rnd),
16333                                       Mask, PassThru, Subtarget, DAG);
16334       }
16335       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16336                                               dl, Op.getValueType(),
16337                                               Src1, Src2, Src3),
16338                                   Mask, PassThru, Subtarget, DAG);
16339     }
16340     case TERLOG_OP_MASK:
16341     case TERLOG_OP_MASKZ: {
16342       SDValue Src1 = Op.getOperand(1);
16343       SDValue Src2 = Op.getOperand(2);
16344       SDValue Src3 = Op.getOperand(3);
16345       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16346       SDValue Mask = Op.getOperand(5);
16347       MVT VT = Op.getSimpleValueType();
16348       SDValue PassThru = Src1;
16349       // Set PassThru element.
16350       if (IntrData->Type == TERLOG_OP_MASKZ)
16351         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16352
16353       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16354                                               Src1, Src2, Src3, Src4),
16355                                   Mask, PassThru, Subtarget, DAG);
16356     }
16357     case FPCLASS: {
16358       // FPclass intrinsics with mask
16359        SDValue Src1 = Op.getOperand(1);
16360        MVT VT = Src1.getSimpleValueType();
16361        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16362        SDValue Imm = Op.getOperand(2);
16363        SDValue Mask = Op.getOperand(3);
16364        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16365                                      Mask.getSimpleValueType().getSizeInBits());
16366        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16367        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16368                                                  DAG.getTargetConstant(0, dl, MaskVT),
16369                                                  Subtarget, DAG);
16370        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16371                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16372                                  DAG.getIntPtrConstant(0, dl));
16373        return DAG.getBitcast(Op.getValueType(), Res);
16374     }
16375     case FPCLASSS: {
16376       SDValue Src1 = Op.getOperand(1);
16377       SDValue Imm = Op.getOperand(2);
16378       SDValue Mask = Op.getOperand(3);
16379       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16380       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16381         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16382       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16383     }
16384     case CMP_MASK:
16385     case CMP_MASK_CC: {
16386       // Comparison intrinsics with masks.
16387       // Example of transformation:
16388       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16389       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16390       // (i8 (bitcast
16391       //   (v8i1 (insert_subvector undef,
16392       //           (v2i1 (and (PCMPEQM %a, %b),
16393       //                      (extract_subvector
16394       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16395       MVT VT = Op.getOperand(1).getSimpleValueType();
16396       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16397       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16398       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16399                                        Mask.getSimpleValueType().getSizeInBits());
16400       SDValue Cmp;
16401       if (IntrData->Type == CMP_MASK_CC) {
16402         SDValue CC = Op.getOperand(3);
16403         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16404         // We specify 2 possible opcodes for intrinsics with rounding modes.
16405         // First, we check if the intrinsic may have non-default rounding mode,
16406         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16407         if (IntrData->Opc1 != 0) {
16408           SDValue Rnd = Op.getOperand(5);
16409           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16410               X86::STATIC_ROUNDING::CUR_DIRECTION)
16411             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16412                               Op.getOperand(2), CC, Rnd);
16413         }
16414         //default rounding mode
16415         if(!Cmp.getNode())
16416             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16417                               Op.getOperand(2), CC);
16418
16419       } else {
16420         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16421         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16422                           Op.getOperand(2));
16423       }
16424       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16425                                              DAG.getTargetConstant(0, dl,
16426                                                                    MaskVT),
16427                                              Subtarget, DAG);
16428       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16429                                 DAG.getUNDEF(BitcastVT), CmpMask,
16430                                 DAG.getIntPtrConstant(0, dl));
16431       return DAG.getBitcast(Op.getValueType(), Res);
16432     }
16433     case CMP_MASK_SCALAR_CC: {
16434       SDValue Src1 = Op.getOperand(1);
16435       SDValue Src2 = Op.getOperand(2);
16436       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16437       SDValue Mask = Op.getOperand(4);
16438
16439       SDValue Cmp;
16440       if (IntrData->Opc1 != 0) {
16441         SDValue Rnd = Op.getOperand(5);
16442         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16443             X86::STATIC_ROUNDING::CUR_DIRECTION)
16444           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16445       }
16446       //default rounding mode
16447       if(!Cmp.getNode())
16448         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16449
16450       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16451                                              DAG.getTargetConstant(0, dl,
16452                                                                    MVT::i1),
16453                                              Subtarget, DAG);
16454
16455       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16456                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16457                          DAG.getValueType(MVT::i1));
16458     }
16459     case COMI: { // Comparison intrinsics
16460       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16461       SDValue LHS = Op.getOperand(1);
16462       SDValue RHS = Op.getOperand(2);
16463       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16464       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16465       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16466       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16467                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16468       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16469     }
16470     case VSHIFT:
16471       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16472                                  Op.getOperand(1), Op.getOperand(2), DAG);
16473     case VSHIFT_MASK:
16474       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16475                                                       Op.getSimpleValueType(),
16476                                                       Op.getOperand(1),
16477                                                       Op.getOperand(2), DAG),
16478                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16479                                   DAG);
16480     case COMPRESS_EXPAND_IN_REG: {
16481       SDValue Mask = Op.getOperand(3);
16482       SDValue DataToCompress = Op.getOperand(1);
16483       SDValue PassThru = Op.getOperand(2);
16484       if (isAllOnes(Mask)) // return data as is
16485         return Op.getOperand(1);
16486
16487       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16488                                               DataToCompress),
16489                                   Mask, PassThru, Subtarget, DAG);
16490     }
16491     case BROADCASTM: {
16492       SDValue Mask = Op.getOperand(1);
16493       MVT MaskVT = MVT::getVectorVT(MVT::i1, Mask.getSimpleValueType().getSizeInBits());
16494       Mask = DAG.getBitcast(MaskVT, Mask);
16495       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16496     }
16497     case BLEND: {
16498       SDValue Mask = Op.getOperand(3);
16499       MVT VT = Op.getSimpleValueType();
16500       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16501       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16502                                        Mask.getSimpleValueType().getSizeInBits());
16503       SDLoc dl(Op);
16504       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16505                                   DAG.getBitcast(BitcastVT, Mask),
16506                                   DAG.getIntPtrConstant(0, dl));
16507       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16508                          Op.getOperand(2));
16509     }
16510     default:
16511       break;
16512     }
16513   }
16514
16515   switch (IntNo) {
16516   default: return SDValue();    // Don't custom lower most intrinsics.
16517
16518   case Intrinsic::x86_avx2_permd:
16519   case Intrinsic::x86_avx2_permps:
16520     // Operands intentionally swapped. Mask is last operand to intrinsic,
16521     // but second operand for node/instruction.
16522     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16523                        Op.getOperand(2), Op.getOperand(1));
16524
16525   // ptest and testp intrinsics. The intrinsic these come from are designed to
16526   // return an integer value, not just an instruction so lower it to the ptest
16527   // or testp pattern and a setcc for the result.
16528   case Intrinsic::x86_sse41_ptestz:
16529   case Intrinsic::x86_sse41_ptestc:
16530   case Intrinsic::x86_sse41_ptestnzc:
16531   case Intrinsic::x86_avx_ptestz_256:
16532   case Intrinsic::x86_avx_ptestc_256:
16533   case Intrinsic::x86_avx_ptestnzc_256:
16534   case Intrinsic::x86_avx_vtestz_ps:
16535   case Intrinsic::x86_avx_vtestc_ps:
16536   case Intrinsic::x86_avx_vtestnzc_ps:
16537   case Intrinsic::x86_avx_vtestz_pd:
16538   case Intrinsic::x86_avx_vtestc_pd:
16539   case Intrinsic::x86_avx_vtestnzc_pd:
16540   case Intrinsic::x86_avx_vtestz_ps_256:
16541   case Intrinsic::x86_avx_vtestc_ps_256:
16542   case Intrinsic::x86_avx_vtestnzc_ps_256:
16543   case Intrinsic::x86_avx_vtestz_pd_256:
16544   case Intrinsic::x86_avx_vtestc_pd_256:
16545   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16546     bool IsTestPacked = false;
16547     unsigned X86CC;
16548     switch (IntNo) {
16549     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16550     case Intrinsic::x86_avx_vtestz_ps:
16551     case Intrinsic::x86_avx_vtestz_pd:
16552     case Intrinsic::x86_avx_vtestz_ps_256:
16553     case Intrinsic::x86_avx_vtestz_pd_256:
16554       IsTestPacked = true; // Fallthrough
16555     case Intrinsic::x86_sse41_ptestz:
16556     case Intrinsic::x86_avx_ptestz_256:
16557       // ZF = 1
16558       X86CC = X86::COND_E;
16559       break;
16560     case Intrinsic::x86_avx_vtestc_ps:
16561     case Intrinsic::x86_avx_vtestc_pd:
16562     case Intrinsic::x86_avx_vtestc_ps_256:
16563     case Intrinsic::x86_avx_vtestc_pd_256:
16564       IsTestPacked = true; // Fallthrough
16565     case Intrinsic::x86_sse41_ptestc:
16566     case Intrinsic::x86_avx_ptestc_256:
16567       // CF = 1
16568       X86CC = X86::COND_B;
16569       break;
16570     case Intrinsic::x86_avx_vtestnzc_ps:
16571     case Intrinsic::x86_avx_vtestnzc_pd:
16572     case Intrinsic::x86_avx_vtestnzc_ps_256:
16573     case Intrinsic::x86_avx_vtestnzc_pd_256:
16574       IsTestPacked = true; // Fallthrough
16575     case Intrinsic::x86_sse41_ptestnzc:
16576     case Intrinsic::x86_avx_ptestnzc_256:
16577       // ZF and CF = 0
16578       X86CC = X86::COND_A;
16579       break;
16580     }
16581
16582     SDValue LHS = Op.getOperand(1);
16583     SDValue RHS = Op.getOperand(2);
16584     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16585     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16586     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16587     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16588     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16589   }
16590   case Intrinsic::x86_avx512_kortestz_w:
16591   case Intrinsic::x86_avx512_kortestc_w: {
16592     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16593     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16594     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16595     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16596     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16597     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16598     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16599   }
16600
16601   case Intrinsic::x86_sse42_pcmpistria128:
16602   case Intrinsic::x86_sse42_pcmpestria128:
16603   case Intrinsic::x86_sse42_pcmpistric128:
16604   case Intrinsic::x86_sse42_pcmpestric128:
16605   case Intrinsic::x86_sse42_pcmpistrio128:
16606   case Intrinsic::x86_sse42_pcmpestrio128:
16607   case Intrinsic::x86_sse42_pcmpistris128:
16608   case Intrinsic::x86_sse42_pcmpestris128:
16609   case Intrinsic::x86_sse42_pcmpistriz128:
16610   case Intrinsic::x86_sse42_pcmpestriz128: {
16611     unsigned Opcode;
16612     unsigned X86CC;
16613     switch (IntNo) {
16614     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16615     case Intrinsic::x86_sse42_pcmpistria128:
16616       Opcode = X86ISD::PCMPISTRI;
16617       X86CC = X86::COND_A;
16618       break;
16619     case Intrinsic::x86_sse42_pcmpestria128:
16620       Opcode = X86ISD::PCMPESTRI;
16621       X86CC = X86::COND_A;
16622       break;
16623     case Intrinsic::x86_sse42_pcmpistric128:
16624       Opcode = X86ISD::PCMPISTRI;
16625       X86CC = X86::COND_B;
16626       break;
16627     case Intrinsic::x86_sse42_pcmpestric128:
16628       Opcode = X86ISD::PCMPESTRI;
16629       X86CC = X86::COND_B;
16630       break;
16631     case Intrinsic::x86_sse42_pcmpistrio128:
16632       Opcode = X86ISD::PCMPISTRI;
16633       X86CC = X86::COND_O;
16634       break;
16635     case Intrinsic::x86_sse42_pcmpestrio128:
16636       Opcode = X86ISD::PCMPESTRI;
16637       X86CC = X86::COND_O;
16638       break;
16639     case Intrinsic::x86_sse42_pcmpistris128:
16640       Opcode = X86ISD::PCMPISTRI;
16641       X86CC = X86::COND_S;
16642       break;
16643     case Intrinsic::x86_sse42_pcmpestris128:
16644       Opcode = X86ISD::PCMPESTRI;
16645       X86CC = X86::COND_S;
16646       break;
16647     case Intrinsic::x86_sse42_pcmpistriz128:
16648       Opcode = X86ISD::PCMPISTRI;
16649       X86CC = X86::COND_E;
16650       break;
16651     case Intrinsic::x86_sse42_pcmpestriz128:
16652       Opcode = X86ISD::PCMPESTRI;
16653       X86CC = X86::COND_E;
16654       break;
16655     }
16656     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16657     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16658     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16659     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16660                                 DAG.getConstant(X86CC, dl, MVT::i8),
16661                                 SDValue(PCMP.getNode(), 1));
16662     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16663   }
16664
16665   case Intrinsic::x86_sse42_pcmpistri128:
16666   case Intrinsic::x86_sse42_pcmpestri128: {
16667     unsigned Opcode;
16668     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16669       Opcode = X86ISD::PCMPISTRI;
16670     else
16671       Opcode = X86ISD::PCMPESTRI;
16672
16673     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16674     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16675     return DAG.getNode(Opcode, dl, VTs, NewOps);
16676   }
16677
16678   case Intrinsic::x86_seh_lsda: {
16679     // Compute the symbol for the LSDA. We know it'll get emitted later.
16680     MachineFunction &MF = DAG.getMachineFunction();
16681     SDValue Op1 = Op.getOperand(1);
16682     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16683     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16684         GlobalValue::getRealLinkageName(Fn->getName()));
16685
16686     // Generate a simple absolute symbol reference. This intrinsic is only
16687     // supported on 32-bit Windows, which isn't PIC.
16688     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16689     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16690   }
16691
16692   case Intrinsic::x86_seh_recoverfp: {
16693     SDValue FnOp = Op.getOperand(1);
16694     SDValue IncomingFPOp = Op.getOperand(2);
16695     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16696     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16697     if (!Fn)
16698       report_fatal_error(
16699           "llvm.x86.seh.recoverfp must take a function as the first argument");
16700     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16701   }
16702
16703   case Intrinsic::localaddress: {
16704     // Returns one of the stack, base, or frame pointer registers, depending on
16705     // which is used to reference local variables.
16706     MachineFunction &MF = DAG.getMachineFunction();
16707     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16708     unsigned Reg;
16709     if (RegInfo->hasBasePointer(MF))
16710       Reg = RegInfo->getBaseRegister();
16711     else // This function handles the SP or FP case.
16712       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16713     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16714   }
16715   }
16716 }
16717
16718 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16719                               SDValue Src, SDValue Mask, SDValue Base,
16720                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16721                               const X86Subtarget * Subtarget) {
16722   SDLoc dl(Op);
16723   auto *C = cast<ConstantSDNode>(ScaleOp);
16724   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16725   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16726                              Index.getSimpleValueType().getVectorNumElements());
16727   SDValue MaskInReg;
16728   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16729   if (MaskC)
16730     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16731   else {
16732     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16733                                      Mask.getSimpleValueType().getSizeInBits());
16734
16735     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16736     // are extracted by EXTRACT_SUBVECTOR.
16737     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16738                             DAG.getBitcast(BitcastVT, Mask),
16739                             DAG.getIntPtrConstant(0, dl));
16740   }
16741   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16742   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16743   SDValue Segment = DAG.getRegister(0, MVT::i32);
16744   if (Src.getOpcode() == ISD::UNDEF)
16745     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16746   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16747   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16748   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16749   return DAG.getMergeValues(RetOps, dl);
16750 }
16751
16752 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16753                                SDValue Src, SDValue Mask, SDValue Base,
16754                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16755   SDLoc dl(Op);
16756   auto *C = cast<ConstantSDNode>(ScaleOp);
16757   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16758   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16759   SDValue Segment = DAG.getRegister(0, MVT::i32);
16760   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16761                              Index.getSimpleValueType().getVectorNumElements());
16762   SDValue MaskInReg;
16763   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16764   if (MaskC)
16765     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16766   else {
16767     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16768                                      Mask.getSimpleValueType().getSizeInBits());
16769
16770     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16771     // are extracted by EXTRACT_SUBVECTOR.
16772     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16773                             DAG.getBitcast(BitcastVT, Mask),
16774                             DAG.getIntPtrConstant(0, dl));
16775   }
16776   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16777   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16778   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16779   return SDValue(Res, 1);
16780 }
16781
16782 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16783                                SDValue Mask, SDValue Base, SDValue Index,
16784                                SDValue ScaleOp, SDValue Chain) {
16785   SDLoc dl(Op);
16786   auto *C = cast<ConstantSDNode>(ScaleOp);
16787   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16788   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16789   SDValue Segment = DAG.getRegister(0, MVT::i32);
16790   MVT MaskVT =
16791     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16792   SDValue MaskInReg;
16793   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16794   if (MaskC)
16795     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16796   else
16797     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16798   //SDVTList VTs = DAG.getVTList(MVT::Other);
16799   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16800   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16801   return SDValue(Res, 0);
16802 }
16803
16804 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16805 // read performance monitor counters (x86_rdpmc).
16806 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16807                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16808                               SmallVectorImpl<SDValue> &Results) {
16809   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16810   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16811   SDValue LO, HI;
16812
16813   // The ECX register is used to select the index of the performance counter
16814   // to read.
16815   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16816                                    N->getOperand(2));
16817   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16818
16819   // Reads the content of a 64-bit performance counter and returns it in the
16820   // registers EDX:EAX.
16821   if (Subtarget->is64Bit()) {
16822     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16823     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16824                             LO.getValue(2));
16825   } else {
16826     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16827     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16828                             LO.getValue(2));
16829   }
16830   Chain = HI.getValue(1);
16831
16832   if (Subtarget->is64Bit()) {
16833     // The EAX register is loaded with the low-order 32 bits. The EDX register
16834     // is loaded with the supported high-order bits of the counter.
16835     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16836                               DAG.getConstant(32, DL, MVT::i8));
16837     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16838     Results.push_back(Chain);
16839     return;
16840   }
16841
16842   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16843   SDValue Ops[] = { LO, HI };
16844   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16845   Results.push_back(Pair);
16846   Results.push_back(Chain);
16847 }
16848
16849 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16850 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16851 // also used to custom lower READCYCLECOUNTER nodes.
16852 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16853                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16854                               SmallVectorImpl<SDValue> &Results) {
16855   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16856   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16857   SDValue LO, HI;
16858
16859   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16860   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16861   // and the EAX register is loaded with the low-order 32 bits.
16862   if (Subtarget->is64Bit()) {
16863     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16864     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16865                             LO.getValue(2));
16866   } else {
16867     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16868     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16869                             LO.getValue(2));
16870   }
16871   SDValue Chain = HI.getValue(1);
16872
16873   if (Opcode == X86ISD::RDTSCP_DAG) {
16874     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16875
16876     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16877     // the ECX register. Add 'ecx' explicitly to the chain.
16878     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16879                                      HI.getValue(2));
16880     // Explicitly store the content of ECX at the location passed in input
16881     // to the 'rdtscp' intrinsic.
16882     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16883                          MachinePointerInfo(), false, false, 0);
16884   }
16885
16886   if (Subtarget->is64Bit()) {
16887     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16888     // the EAX register is loaded with the low-order 32 bits.
16889     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16890                               DAG.getConstant(32, DL, MVT::i8));
16891     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16892     Results.push_back(Chain);
16893     return;
16894   }
16895
16896   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16897   SDValue Ops[] = { LO, HI };
16898   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16899   Results.push_back(Pair);
16900   Results.push_back(Chain);
16901 }
16902
16903 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16904                                      SelectionDAG &DAG) {
16905   SmallVector<SDValue, 2> Results;
16906   SDLoc DL(Op);
16907   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16908                           Results);
16909   return DAG.getMergeValues(Results, DL);
16910 }
16911
16912 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16913                                     SelectionDAG &DAG) {
16914   MachineFunction &MF = DAG.getMachineFunction();
16915   const Function *Fn = MF.getFunction();
16916   SDLoc dl(Op);
16917   SDValue Chain = Op.getOperand(0);
16918
16919   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16920          "using llvm.x86.seh.restoreframe requires a frame pointer");
16921
16922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16923   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16924
16925   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16926   unsigned FrameReg =
16927       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16928   unsigned SPReg = RegInfo->getStackRegister();
16929   unsigned SlotSize = RegInfo->getSlotSize();
16930
16931   // Get incoming EBP.
16932   SDValue IncomingEBP =
16933       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16934
16935   // SP is saved in the first field of every registration node, so load
16936   // [EBP-RegNodeSize] into SP.
16937   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16938   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16939                                DAG.getConstant(-RegNodeSize, dl, VT));
16940   SDValue NewSP =
16941       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16942                   false, VT.getScalarSizeInBits() / 8);
16943   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16944
16945   if (!RegInfo->needsStackRealignment(MF)) {
16946     // Adjust EBP to point back to the original frame position.
16947     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16948     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16949   } else {
16950     assert(RegInfo->hasBasePointer(MF) &&
16951            "functions with Win32 EH must use frame or base pointer register");
16952
16953     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16954     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16955     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16956
16957     // Reload the spilled EBP value, now that the stack and base pointers are
16958     // set up.
16959     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16960     X86FI->setHasSEHFramePtrSave(true);
16961     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16962     X86FI->setSEHFramePtrSaveIndex(FI);
16963     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16964                                 MachinePointerInfo(), false, false, false,
16965                                 VT.getScalarSizeInBits() / 8);
16966     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16967   }
16968
16969   return Chain;
16970 }
16971
16972 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
16973   MachineFunction &MF = DAG.getMachineFunction();
16974   SDValue Chain = Op.getOperand(0);
16975   SDValue RegNode = Op.getOperand(2);
16976   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
16977   if (!EHInfo)
16978     report_fatal_error("EH registrations only live in functions using WinEH");
16979
16980   // Cast the operand to an alloca, and remember the frame index.
16981   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
16982   if (!FINode)
16983     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
16984   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
16985
16986   // Return the chain operand without making any DAG nodes.
16987   return Chain;
16988 }
16989
16990 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16991 /// return truncate Store/MaskedStore Node
16992 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16993                                                SelectionDAG &DAG,
16994                                                MVT ElementType) {
16995   SDLoc dl(Op);
16996   SDValue Mask = Op.getOperand(4);
16997   SDValue DataToTruncate = Op.getOperand(3);
16998   SDValue Addr = Op.getOperand(2);
16999   SDValue Chain = Op.getOperand(0);
17000
17001   MVT VT  = DataToTruncate.getSimpleValueType();
17002   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17003
17004   if (isAllOnes(Mask)) // return just a truncate store
17005     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17006                              MachinePointerInfo(), SVT, false, false,
17007                              SVT.getScalarSizeInBits()/8);
17008
17009   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17010   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17011                                    Mask.getSimpleValueType().getSizeInBits());
17012   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17013   // are extracted by EXTRACT_SUBVECTOR.
17014   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17015                               DAG.getBitcast(BitcastVT, Mask),
17016                               DAG.getIntPtrConstant(0, dl));
17017
17018   MachineMemOperand *MMO = DAG.getMachineFunction().
17019     getMachineMemOperand(MachinePointerInfo(),
17020                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17021                          SVT.getScalarSizeInBits()/8);
17022
17023   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17024                             VMask, SVT, MMO, true);
17025 }
17026
17027 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17028                                       SelectionDAG &DAG) {
17029   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17030
17031   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17032   if (!IntrData) {
17033     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
17034       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
17035     else if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17036       return MarkEHRegistrationNode(Op, DAG);
17037     return SDValue();
17038   }
17039
17040   SDLoc dl(Op);
17041   switch(IntrData->Type) {
17042   default: llvm_unreachable("Unknown Intrinsic Type");
17043   case RDSEED:
17044   case RDRAND: {
17045     // Emit the node with the right value type.
17046     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17047     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17048
17049     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17050     // Otherwise return the value from Rand, which is always 0, casted to i32.
17051     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17052                       DAG.getConstant(1, dl, Op->getValueType(1)),
17053                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17054                       SDValue(Result.getNode(), 1) };
17055     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17056                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17057                                   Ops);
17058
17059     // Return { result, isValid, chain }.
17060     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17061                        SDValue(Result.getNode(), 2));
17062   }
17063   case GATHER: {
17064   //gather(v1, mask, index, base, scale);
17065     SDValue Chain = Op.getOperand(0);
17066     SDValue Src   = Op.getOperand(2);
17067     SDValue Base  = Op.getOperand(3);
17068     SDValue Index = Op.getOperand(4);
17069     SDValue Mask  = Op.getOperand(5);
17070     SDValue Scale = Op.getOperand(6);
17071     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17072                          Chain, Subtarget);
17073   }
17074   case SCATTER: {
17075   //scatter(base, mask, index, v1, scale);
17076     SDValue Chain = Op.getOperand(0);
17077     SDValue Base  = Op.getOperand(2);
17078     SDValue Mask  = Op.getOperand(3);
17079     SDValue Index = Op.getOperand(4);
17080     SDValue Src   = Op.getOperand(5);
17081     SDValue Scale = Op.getOperand(6);
17082     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17083                           Scale, Chain);
17084   }
17085   case PREFETCH: {
17086     SDValue Hint = Op.getOperand(6);
17087     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17088     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17089     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17090     SDValue Chain = Op.getOperand(0);
17091     SDValue Mask  = Op.getOperand(2);
17092     SDValue Index = Op.getOperand(3);
17093     SDValue Base  = Op.getOperand(4);
17094     SDValue Scale = Op.getOperand(5);
17095     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17096   }
17097   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17098   case RDTSC: {
17099     SmallVector<SDValue, 2> Results;
17100     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17101                             Results);
17102     return DAG.getMergeValues(Results, dl);
17103   }
17104   // Read Performance Monitoring Counters.
17105   case RDPMC: {
17106     SmallVector<SDValue, 2> Results;
17107     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17108     return DAG.getMergeValues(Results, dl);
17109   }
17110   // XTEST intrinsics.
17111   case XTEST: {
17112     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17113     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17114     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17115                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17116                                 InTrans);
17117     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17118     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17119                        Ret, SDValue(InTrans.getNode(), 1));
17120   }
17121   // ADC/ADCX/SBB
17122   case ADX: {
17123     SmallVector<SDValue, 2> Results;
17124     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17125     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17126     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17127                                 DAG.getConstant(-1, dl, MVT::i8));
17128     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17129                               Op.getOperand(4), GenCF.getValue(1));
17130     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17131                                  Op.getOperand(5), MachinePointerInfo(),
17132                                  false, false, 0);
17133     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17134                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17135                                 Res.getValue(1));
17136     Results.push_back(SetCC);
17137     Results.push_back(Store);
17138     return DAG.getMergeValues(Results, dl);
17139   }
17140   case COMPRESS_TO_MEM: {
17141     SDLoc dl(Op);
17142     SDValue Mask = Op.getOperand(4);
17143     SDValue DataToCompress = Op.getOperand(3);
17144     SDValue Addr = Op.getOperand(2);
17145     SDValue Chain = Op.getOperand(0);
17146
17147     MVT VT = DataToCompress.getSimpleValueType();
17148     if (isAllOnes(Mask)) // return just a store
17149       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17150                           MachinePointerInfo(), false, false,
17151                           VT.getScalarSizeInBits()/8);
17152
17153     SDValue Compressed =
17154       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17155                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17156     return DAG.getStore(Chain, dl, Compressed, Addr,
17157                         MachinePointerInfo(), false, false,
17158                         VT.getScalarSizeInBits()/8);
17159   }
17160   case TRUNCATE_TO_MEM_VI8:
17161     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17162   case TRUNCATE_TO_MEM_VI16:
17163     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17164   case TRUNCATE_TO_MEM_VI32:
17165     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17166   case EXPAND_FROM_MEM: {
17167     SDLoc dl(Op);
17168     SDValue Mask = Op.getOperand(4);
17169     SDValue PassThru = Op.getOperand(3);
17170     SDValue Addr = Op.getOperand(2);
17171     SDValue Chain = Op.getOperand(0);
17172     MVT VT = Op.getSimpleValueType();
17173
17174     if (isAllOnes(Mask)) // return just a load
17175       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17176                          false, VT.getScalarSizeInBits()/8);
17177
17178     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17179                                        false, false, false,
17180                                        VT.getScalarSizeInBits()/8);
17181
17182     SDValue Results[] = {
17183       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17184                            Mask, PassThru, Subtarget, DAG), Chain};
17185     return DAG.getMergeValues(Results, dl);
17186   }
17187   }
17188 }
17189
17190 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17191                                            SelectionDAG &DAG) const {
17192   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17193   MFI->setReturnAddressIsTaken(true);
17194
17195   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17196     return SDValue();
17197
17198   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17199   SDLoc dl(Op);
17200   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17201
17202   if (Depth > 0) {
17203     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17204     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17205     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17206     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17207                        DAG.getNode(ISD::ADD, dl, PtrVT,
17208                                    FrameAddr, Offset),
17209                        MachinePointerInfo(), false, false, false, 0);
17210   }
17211
17212   // Just load the return address.
17213   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17214   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17215                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17216 }
17217
17218 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17219   MachineFunction &MF = DAG.getMachineFunction();
17220   MachineFrameInfo *MFI = MF.getFrameInfo();
17221   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17222   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17223   EVT VT = Op.getValueType();
17224
17225   MFI->setFrameAddressIsTaken(true);
17226
17227   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17228     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17229     // is not possible to crawl up the stack without looking at the unwind codes
17230     // simultaneously.
17231     int FrameAddrIndex = FuncInfo->getFAIndex();
17232     if (!FrameAddrIndex) {
17233       // Set up a frame object for the return address.
17234       unsigned SlotSize = RegInfo->getSlotSize();
17235       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17236           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17237       FuncInfo->setFAIndex(FrameAddrIndex);
17238     }
17239     return DAG.getFrameIndex(FrameAddrIndex, VT);
17240   }
17241
17242   unsigned FrameReg =
17243       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17244   SDLoc dl(Op);  // FIXME probably not meaningful
17245   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17246   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17247           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17248          "Invalid Frame Register!");
17249   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17250   while (Depth--)
17251     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17252                             MachinePointerInfo(),
17253                             false, false, false, 0);
17254   return FrameAddr;
17255 }
17256
17257 // FIXME? Maybe this could be a TableGen attribute on some registers and
17258 // this table could be generated automatically from RegInfo.
17259 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17260                                               SelectionDAG &DAG) const {
17261   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17262   const MachineFunction &MF = DAG.getMachineFunction();
17263
17264   unsigned Reg = StringSwitch<unsigned>(RegName)
17265                        .Case("esp", X86::ESP)
17266                        .Case("rsp", X86::RSP)
17267                        .Case("ebp", X86::EBP)
17268                        .Case("rbp", X86::RBP)
17269                        .Default(0);
17270
17271   if (Reg == X86::EBP || Reg == X86::RBP) {
17272     if (!TFI.hasFP(MF))
17273       report_fatal_error("register " + StringRef(RegName) +
17274                          " is allocatable: function has no frame pointer");
17275 #ifndef NDEBUG
17276     else {
17277       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17278       unsigned FrameReg =
17279           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17280       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17281              "Invalid Frame Register!");
17282     }
17283 #endif
17284   }
17285
17286   if (Reg)
17287     return Reg;
17288
17289   report_fatal_error("Invalid register name global variable");
17290 }
17291
17292 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17293                                                      SelectionDAG &DAG) const {
17294   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17295   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17296 }
17297
17298 unsigned X86TargetLowering::getExceptionPointerRegister(
17299     const Constant *PersonalityFn) const {
17300   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17301     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17302
17303   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17304 }
17305
17306 unsigned X86TargetLowering::getExceptionSelectorRegister(
17307     const Constant *PersonalityFn) const {
17308   // Funclet personalities don't use selectors (the runtime does the selection).
17309   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17310   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17311 }
17312
17313 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17314   SDValue Chain     = Op.getOperand(0);
17315   SDValue Offset    = Op.getOperand(1);
17316   SDValue Handler   = Op.getOperand(2);
17317   SDLoc dl      (Op);
17318
17319   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17320   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17321   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17322   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17323           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17324          "Invalid Frame Register!");
17325   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17326   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17327
17328   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17329                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17330                                                        dl));
17331   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17332   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17333                        false, false, 0);
17334   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17335
17336   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17337                      DAG.getRegister(StoreAddrReg, PtrVT));
17338 }
17339
17340 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17341                                                SelectionDAG &DAG) const {
17342   SDLoc DL(Op);
17343   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17344                      DAG.getVTList(MVT::i32, MVT::Other),
17345                      Op.getOperand(0), Op.getOperand(1));
17346 }
17347
17348 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17349                                                 SelectionDAG &DAG) const {
17350   SDLoc DL(Op);
17351   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17352                      Op.getOperand(0), Op.getOperand(1));
17353 }
17354
17355 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17356   return Op.getOperand(0);
17357 }
17358
17359 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17360                                                 SelectionDAG &DAG) const {
17361   SDValue Root = Op.getOperand(0);
17362   SDValue Trmp = Op.getOperand(1); // trampoline
17363   SDValue FPtr = Op.getOperand(2); // nested function
17364   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17365   SDLoc dl (Op);
17366
17367   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17368   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17369
17370   if (Subtarget->is64Bit()) {
17371     SDValue OutChains[6];
17372
17373     // Large code-model.
17374     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17375     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17376
17377     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17378     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17379
17380     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17381
17382     // Load the pointer to the nested function into R11.
17383     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17384     SDValue Addr = Trmp;
17385     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17386                                 Addr, MachinePointerInfo(TrmpAddr),
17387                                 false, false, 0);
17388
17389     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17390                        DAG.getConstant(2, dl, MVT::i64));
17391     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17392                                 MachinePointerInfo(TrmpAddr, 2),
17393                                 false, false, 2);
17394
17395     // Load the 'nest' parameter value into R10.
17396     // R10 is specified in X86CallingConv.td
17397     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17398     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17399                        DAG.getConstant(10, dl, MVT::i64));
17400     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17401                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17402                                 false, false, 0);
17403
17404     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17405                        DAG.getConstant(12, dl, MVT::i64));
17406     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17407                                 MachinePointerInfo(TrmpAddr, 12),
17408                                 false, false, 2);
17409
17410     // Jump to the nested function.
17411     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17412     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17413                        DAG.getConstant(20, dl, MVT::i64));
17414     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17415                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17416                                 false, false, 0);
17417
17418     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17419     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17420                        DAG.getConstant(22, dl, MVT::i64));
17421     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17422                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17423                                 false, false, 0);
17424
17425     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17426   } else {
17427     const Function *Func =
17428       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17429     CallingConv::ID CC = Func->getCallingConv();
17430     unsigned NestReg;
17431
17432     switch (CC) {
17433     default:
17434       llvm_unreachable("Unsupported calling convention");
17435     case CallingConv::C:
17436     case CallingConv::X86_StdCall: {
17437       // Pass 'nest' parameter in ECX.
17438       // Must be kept in sync with X86CallingConv.td
17439       NestReg = X86::ECX;
17440
17441       // Check that ECX wasn't needed by an 'inreg' parameter.
17442       FunctionType *FTy = Func->getFunctionType();
17443       const AttributeSet &Attrs = Func->getAttributes();
17444
17445       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17446         unsigned InRegCount = 0;
17447         unsigned Idx = 1;
17448
17449         for (FunctionType::param_iterator I = FTy->param_begin(),
17450              E = FTy->param_end(); I != E; ++I, ++Idx)
17451           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17452             auto &DL = DAG.getDataLayout();
17453             // FIXME: should only count parameters that are lowered to integers.
17454             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17455           }
17456
17457         if (InRegCount > 2) {
17458           report_fatal_error("Nest register in use - reduce number of inreg"
17459                              " parameters!");
17460         }
17461       }
17462       break;
17463     }
17464     case CallingConv::X86_FastCall:
17465     case CallingConv::X86_ThisCall:
17466     case CallingConv::Fast:
17467       // Pass 'nest' parameter in EAX.
17468       // Must be kept in sync with X86CallingConv.td
17469       NestReg = X86::EAX;
17470       break;
17471     }
17472
17473     SDValue OutChains[4];
17474     SDValue Addr, Disp;
17475
17476     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17477                        DAG.getConstant(10, dl, MVT::i32));
17478     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17479
17480     // This is storing the opcode for MOV32ri.
17481     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17482     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17483     OutChains[0] = DAG.getStore(Root, dl,
17484                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17485                                 Trmp, MachinePointerInfo(TrmpAddr),
17486                                 false, false, 0);
17487
17488     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17489                        DAG.getConstant(1, dl, MVT::i32));
17490     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17491                                 MachinePointerInfo(TrmpAddr, 1),
17492                                 false, false, 1);
17493
17494     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17495     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17496                        DAG.getConstant(5, dl, MVT::i32));
17497     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17498                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17499                                 false, false, 1);
17500
17501     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17502                        DAG.getConstant(6, dl, MVT::i32));
17503     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17504                                 MachinePointerInfo(TrmpAddr, 6),
17505                                 false, false, 1);
17506
17507     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17508   }
17509 }
17510
17511 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17512                                             SelectionDAG &DAG) const {
17513   /*
17514    The rounding mode is in bits 11:10 of FPSR, and has the following
17515    settings:
17516      00 Round to nearest
17517      01 Round to -inf
17518      10 Round to +inf
17519      11 Round to 0
17520
17521   FLT_ROUNDS, on the other hand, expects the following:
17522     -1 Undefined
17523      0 Round to 0
17524      1 Round to nearest
17525      2 Round to +inf
17526      3 Round to -inf
17527
17528   To perform the conversion, we do:
17529     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17530   */
17531
17532   MachineFunction &MF = DAG.getMachineFunction();
17533   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17534   unsigned StackAlignment = TFI.getStackAlignment();
17535   MVT VT = Op.getSimpleValueType();
17536   SDLoc DL(Op);
17537
17538   // Save FP Control Word to stack slot
17539   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17540   SDValue StackSlot =
17541       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17542
17543   MachineMemOperand *MMO =
17544       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17545                               MachineMemOperand::MOStore, 2, 2);
17546
17547   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17548   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17549                                           DAG.getVTList(MVT::Other),
17550                                           Ops, MVT::i16, MMO);
17551
17552   // Load FP Control Word from stack slot
17553   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17554                             MachinePointerInfo(), false, false, false, 0);
17555
17556   // Transform as necessary
17557   SDValue CWD1 =
17558     DAG.getNode(ISD::SRL, DL, MVT::i16,
17559                 DAG.getNode(ISD::AND, DL, MVT::i16,
17560                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17561                 DAG.getConstant(11, DL, MVT::i8));
17562   SDValue CWD2 =
17563     DAG.getNode(ISD::SRL, DL, MVT::i16,
17564                 DAG.getNode(ISD::AND, DL, MVT::i16,
17565                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17566                 DAG.getConstant(9, DL, MVT::i8));
17567
17568   SDValue RetVal =
17569     DAG.getNode(ISD::AND, DL, MVT::i16,
17570                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17571                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17572                             DAG.getConstant(1, DL, MVT::i16)),
17573                 DAG.getConstant(3, DL, MVT::i16));
17574
17575   return DAG.getNode((VT.getSizeInBits() < 16 ?
17576                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17577 }
17578
17579 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17580 //
17581 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17582 //    to 512-bit vector.
17583 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17584 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17585 //    split the vector, perform operation on it's Lo a Hi part and
17586 //    concatenate the results.
17587 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17588   SDLoc dl(Op);
17589   MVT VT = Op.getSimpleValueType();
17590   MVT EltVT = VT.getVectorElementType();
17591   unsigned NumElems = VT.getVectorNumElements();
17592
17593   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17594     // Extend to 512 bit vector.
17595     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17596               "Unsupported value type for operation");
17597
17598     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17599     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17600                                  DAG.getUNDEF(NewVT),
17601                                  Op.getOperand(0),
17602                                  DAG.getIntPtrConstant(0, dl));
17603     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17604
17605     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17606                        DAG.getIntPtrConstant(0, dl));
17607   }
17608
17609   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17610           "Unsupported element type");
17611
17612   if (16 < NumElems) {
17613     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17614     SDValue Lo, Hi;
17615     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17616     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17617
17618     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17619     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17620
17621     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17622   }
17623
17624   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17625
17626   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17627           "Unsupported value type for operation");
17628
17629   // Use native supported vector instruction vplzcntd.
17630   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17631   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17632   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17633   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17634
17635   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17636 }
17637
17638 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17639                          SelectionDAG &DAG) {
17640   MVT VT = Op.getSimpleValueType();
17641   MVT OpVT = VT;
17642   unsigned NumBits = VT.getSizeInBits();
17643   SDLoc dl(Op);
17644
17645   if (VT.isVector() && Subtarget->hasAVX512())
17646     return LowerVectorCTLZ_AVX512(Op, DAG);
17647
17648   Op = Op.getOperand(0);
17649   if (VT == MVT::i8) {
17650     // Zero extend to i32 since there is not an i8 bsr.
17651     OpVT = MVT::i32;
17652     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17653   }
17654
17655   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17656   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17657   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17658
17659   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17660   SDValue Ops[] = {
17661     Op,
17662     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17663     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17664     Op.getValue(1)
17665   };
17666   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17667
17668   // Finally xor with NumBits-1.
17669   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17670                    DAG.getConstant(NumBits - 1, dl, OpVT));
17671
17672   if (VT == MVT::i8)
17673     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17674   return Op;
17675 }
17676
17677 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17678                                     SelectionDAG &DAG) {
17679   MVT VT = Op.getSimpleValueType();
17680   EVT OpVT = VT;
17681   unsigned NumBits = VT.getSizeInBits();
17682   SDLoc dl(Op);
17683
17684   if (VT.isVector() && Subtarget->hasAVX512())
17685     return LowerVectorCTLZ_AVX512(Op, DAG);
17686
17687   Op = Op.getOperand(0);
17688   if (VT == MVT::i8) {
17689     // Zero extend to i32 since there is not an i8 bsr.
17690     OpVT = MVT::i32;
17691     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17692   }
17693
17694   // Issue a bsr (scan bits in reverse).
17695   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17696   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17697
17698   // And xor with NumBits-1.
17699   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17700                    DAG.getConstant(NumBits - 1, dl, OpVT));
17701
17702   if (VT == MVT::i8)
17703     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17704   return Op;
17705 }
17706
17707 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17708   MVT VT = Op.getSimpleValueType();
17709   unsigned NumBits = VT.getScalarSizeInBits();
17710   SDLoc dl(Op);
17711
17712   if (VT.isVector()) {
17713     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17714
17715     SDValue N0 = Op.getOperand(0);
17716     SDValue Zero = DAG.getConstant(0, dl, VT);
17717
17718     // lsb(x) = (x & -x)
17719     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17720                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17721
17722     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17723     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17724         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17725       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17726       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17727                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17728     }
17729
17730     // cttz(x) = ctpop(lsb - 1)
17731     SDValue One = DAG.getConstant(1, dl, VT);
17732     return DAG.getNode(ISD::CTPOP, dl, VT,
17733                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17734   }
17735
17736   assert(Op.getOpcode() == ISD::CTTZ &&
17737          "Only scalar CTTZ requires custom lowering");
17738
17739   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17740   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17741   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17742
17743   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17744   SDValue Ops[] = {
17745     Op,
17746     DAG.getConstant(NumBits, dl, VT),
17747     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17748     Op.getValue(1)
17749   };
17750   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17751 }
17752
17753 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17754 // ones, and then concatenate the result back.
17755 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17756   MVT VT = Op.getSimpleValueType();
17757
17758   assert(VT.is256BitVector() && VT.isInteger() &&
17759          "Unsupported value type for operation");
17760
17761   unsigned NumElems = VT.getVectorNumElements();
17762   SDLoc dl(Op);
17763
17764   // Extract the LHS vectors
17765   SDValue LHS = Op.getOperand(0);
17766   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17767   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17768
17769   // Extract the RHS vectors
17770   SDValue RHS = Op.getOperand(1);
17771   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17772   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17773
17774   MVT EltVT = VT.getVectorElementType();
17775   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17776
17777   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17778                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17779                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17780 }
17781
17782 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17783   if (Op.getValueType() == MVT::i1)
17784     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17785                        Op.getOperand(0), Op.getOperand(1));
17786   assert(Op.getSimpleValueType().is256BitVector() &&
17787          Op.getSimpleValueType().isInteger() &&
17788          "Only handle AVX 256-bit vector integer operation");
17789   return Lower256IntArith(Op, DAG);
17790 }
17791
17792 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17793   if (Op.getValueType() == MVT::i1)
17794     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17795                        Op.getOperand(0), Op.getOperand(1));
17796   assert(Op.getSimpleValueType().is256BitVector() &&
17797          Op.getSimpleValueType().isInteger() &&
17798          "Only handle AVX 256-bit vector integer operation");
17799   return Lower256IntArith(Op, DAG);
17800 }
17801
17802 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17803   assert(Op.getSimpleValueType().is256BitVector() &&
17804          Op.getSimpleValueType().isInteger() &&
17805          "Only handle AVX 256-bit vector integer operation");
17806   return Lower256IntArith(Op, DAG);
17807 }
17808
17809 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17810                         SelectionDAG &DAG) {
17811   SDLoc dl(Op);
17812   MVT VT = Op.getSimpleValueType();
17813
17814   if (VT == MVT::i1)
17815     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17816
17817   // Decompose 256-bit ops into smaller 128-bit ops.
17818   if (VT.is256BitVector() && !Subtarget->hasInt256())
17819     return Lower256IntArith(Op, DAG);
17820
17821   SDValue A = Op.getOperand(0);
17822   SDValue B = Op.getOperand(1);
17823
17824   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17825   // pairs, multiply and truncate.
17826   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17827     if (Subtarget->hasInt256()) {
17828       if (VT == MVT::v32i8) {
17829         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17830         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17831         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17832         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17833         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17834         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17835         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17836         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17837                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17838                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17839       }
17840
17841       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17842       return DAG.getNode(
17843           ISD::TRUNCATE, dl, VT,
17844           DAG.getNode(ISD::MUL, dl, ExVT,
17845                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17846                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17847     }
17848
17849     assert(VT == MVT::v16i8 &&
17850            "Pre-AVX2 support only supports v16i8 multiplication");
17851     MVT ExVT = MVT::v8i16;
17852
17853     // Extract the lo parts and sign extend to i16
17854     SDValue ALo, BLo;
17855     if (Subtarget->hasSSE41()) {
17856       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17857       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17858     } else {
17859       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17860                               -1, 4, -1, 5, -1, 6, -1, 7};
17861       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17862       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17863       ALo = DAG.getBitcast(ExVT, ALo);
17864       BLo = DAG.getBitcast(ExVT, BLo);
17865       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17866       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17867     }
17868
17869     // Extract the hi parts and sign extend to i16
17870     SDValue AHi, BHi;
17871     if (Subtarget->hasSSE41()) {
17872       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17873                               -1, -1, -1, -1, -1, -1, -1, -1};
17874       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17875       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17876       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17877       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17878     } else {
17879       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17880                               -1, 12, -1, 13, -1, 14, -1, 15};
17881       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17882       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17883       AHi = DAG.getBitcast(ExVT, AHi);
17884       BHi = DAG.getBitcast(ExVT, BHi);
17885       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17886       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17887     }
17888
17889     // Multiply, mask the lower 8bits of the lo/hi results and pack
17890     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17891     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17892     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17893     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17894     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17895   }
17896
17897   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17898   if (VT == MVT::v4i32) {
17899     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17900            "Should not custom lower when pmuldq is available!");
17901
17902     // Extract the odd parts.
17903     static const int UnpackMask[] = { 1, -1, 3, -1 };
17904     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17905     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17906
17907     // Multiply the even parts.
17908     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17909     // Now multiply odd parts.
17910     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17911
17912     Evens = DAG.getBitcast(VT, Evens);
17913     Odds = DAG.getBitcast(VT, Odds);
17914
17915     // Merge the two vectors back together with a shuffle. This expands into 2
17916     // shuffles.
17917     static const int ShufMask[] = { 0, 4, 2, 6 };
17918     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17919   }
17920
17921   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17922          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17923
17924   //  Ahi = psrlqi(a, 32);
17925   //  Bhi = psrlqi(b, 32);
17926   //
17927   //  AloBlo = pmuludq(a, b);
17928   //  AloBhi = pmuludq(a, Bhi);
17929   //  AhiBlo = pmuludq(Ahi, b);
17930
17931   //  AloBhi = psllqi(AloBhi, 32);
17932   //  AhiBlo = psllqi(AhiBlo, 32);
17933   //  return AloBlo + AloBhi + AhiBlo;
17934
17935   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17936   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17937
17938   SDValue AhiBlo = Ahi;
17939   SDValue AloBhi = Bhi;
17940   // Bit cast to 32-bit vectors for MULUDQ
17941   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17942                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17943   A = DAG.getBitcast(MulVT, A);
17944   B = DAG.getBitcast(MulVT, B);
17945   Ahi = DAG.getBitcast(MulVT, Ahi);
17946   Bhi = DAG.getBitcast(MulVT, Bhi);
17947
17948   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17949   // After shifting right const values the result may be all-zero.
17950   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17951     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17952     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17953   }
17954   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17955     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17956     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17957   }
17958
17959   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17960   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17961 }
17962
17963 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17964   assert(Subtarget->isTargetWin64() && "Unexpected target");
17965   EVT VT = Op.getValueType();
17966   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17967          "Unexpected return type for lowering");
17968
17969   RTLIB::Libcall LC;
17970   bool isSigned;
17971   switch (Op->getOpcode()) {
17972   default: llvm_unreachable("Unexpected request for libcall!");
17973   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17974   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17975   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17976   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17977   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17978   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17979   }
17980
17981   SDLoc dl(Op);
17982   SDValue InChain = DAG.getEntryNode();
17983
17984   TargetLowering::ArgListTy Args;
17985   TargetLowering::ArgListEntry Entry;
17986   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17987     EVT ArgVT = Op->getOperand(i).getValueType();
17988     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17989            "Unexpected argument type for lowering");
17990     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17991     Entry.Node = StackPtr;
17992     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17993                            false, false, 16);
17994     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17995     Entry.Ty = PointerType::get(ArgTy,0);
17996     Entry.isSExt = false;
17997     Entry.isZExt = false;
17998     Args.push_back(Entry);
17999   }
18000
18001   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18002                                          getPointerTy(DAG.getDataLayout()));
18003
18004   TargetLowering::CallLoweringInfo CLI(DAG);
18005   CLI.setDebugLoc(dl).setChain(InChain)
18006     .setCallee(getLibcallCallingConv(LC),
18007                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18008                Callee, std::move(Args), 0)
18009     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18010
18011   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18012   return DAG.getBitcast(VT, CallInfo.first);
18013 }
18014
18015 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18016                              SelectionDAG &DAG) {
18017   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18018   MVT VT = Op0.getSimpleValueType();
18019   SDLoc dl(Op);
18020
18021   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18022          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18023
18024   // PMULxD operations multiply each even value (starting at 0) of LHS with
18025   // the related value of RHS and produce a widen result.
18026   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18027   // => <2 x i64> <ae|cg>
18028   //
18029   // In other word, to have all the results, we need to perform two PMULxD:
18030   // 1. one with the even values.
18031   // 2. one with the odd values.
18032   // To achieve #2, with need to place the odd values at an even position.
18033   //
18034   // Place the odd value at an even position (basically, shift all values 1
18035   // step to the left):
18036   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18037   // <a|b|c|d> => <b|undef|d|undef>
18038   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18039   // <e|f|g|h> => <f|undef|h|undef>
18040   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18041
18042   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18043   // ints.
18044   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18045   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18046   unsigned Opcode =
18047       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18048   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18049   // => <2 x i64> <ae|cg>
18050   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18051   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18052   // => <2 x i64> <bf|dh>
18053   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18054
18055   // Shuffle it back into the right order.
18056   SDValue Highs, Lows;
18057   if (VT == MVT::v8i32) {
18058     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18059     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18060     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18061     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18062   } else {
18063     const int HighMask[] = {1, 5, 3, 7};
18064     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18065     const int LowMask[] = {0, 4, 2, 6};
18066     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18067   }
18068
18069   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18070   // unsigned multiply.
18071   if (IsSigned && !Subtarget->hasSSE41()) {
18072     SDValue ShAmt = DAG.getConstant(
18073         31, dl,
18074         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18075     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18076                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18077     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18078                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18079
18080     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18081     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18082   }
18083
18084   // The first result of MUL_LOHI is actually the low value, followed by the
18085   // high value.
18086   SDValue Ops[] = {Lows, Highs};
18087   return DAG.getMergeValues(Ops, dl);
18088 }
18089
18090 // Return true if the required (according to Opcode) shift-imm form is natively
18091 // supported by the Subtarget
18092 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18093                                         unsigned Opcode) {
18094   if (VT.getScalarSizeInBits() < 16)
18095     return false;
18096
18097   if (VT.is512BitVector() &&
18098       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18099     return true;
18100
18101   bool LShift = VT.is128BitVector() ||
18102     (VT.is256BitVector() && Subtarget->hasInt256());
18103
18104   bool AShift = LShift && (Subtarget->hasVLX() ||
18105     (VT != MVT::v2i64 && VT != MVT::v4i64));
18106   return (Opcode == ISD::SRA) ? AShift : LShift;
18107 }
18108
18109 // The shift amount is a variable, but it is the same for all vector lanes.
18110 // These instructions are defined together with shift-immediate.
18111 static
18112 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18113                                       unsigned Opcode) {
18114   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18115 }
18116
18117 // Return true if the required (according to Opcode) variable-shift form is
18118 // natively supported by the Subtarget
18119 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18120                                     unsigned Opcode) {
18121
18122   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18123     return false;
18124
18125   // vXi16 supported only on AVX-512, BWI
18126   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18127     return false;
18128
18129   if (VT.is512BitVector() || Subtarget->hasVLX())
18130     return true;
18131
18132   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18133   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18134   return (Opcode == ISD::SRA) ? AShift : LShift;
18135 }
18136
18137 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18138                                          const X86Subtarget *Subtarget) {
18139   MVT VT = Op.getSimpleValueType();
18140   SDLoc dl(Op);
18141   SDValue R = Op.getOperand(0);
18142   SDValue Amt = Op.getOperand(1);
18143
18144   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18145     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18146
18147   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18148     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18149     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18150     SDValue Ex = DAG.getBitcast(ExVT, R);
18151
18152     if (ShiftAmt >= 32) {
18153       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18154       SDValue Upper =
18155           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18156       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18157                                                  ShiftAmt - 32, DAG);
18158       if (VT == MVT::v2i64)
18159         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18160       if (VT == MVT::v4i64)
18161         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18162                                   {9, 1, 11, 3, 13, 5, 15, 7});
18163     } else {
18164       // SRA upper i32, SHL whole i64 and select lower i32.
18165       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18166                                                  ShiftAmt, DAG);
18167       SDValue Lower =
18168           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18169       Lower = DAG.getBitcast(ExVT, Lower);
18170       if (VT == MVT::v2i64)
18171         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18172       if (VT == MVT::v4i64)
18173         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18174                                   {8, 1, 10, 3, 12, 5, 14, 7});
18175     }
18176     return DAG.getBitcast(VT, Ex);
18177   };
18178
18179   // Optimize shl/srl/sra with constant shift amount.
18180   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18181     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18182       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18183
18184       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18185         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18186
18187       // i64 SRA needs to be performed as partial shifts.
18188       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18189           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18190         return ArithmeticShiftRight64(ShiftAmt);
18191
18192       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18193         unsigned NumElts = VT.getVectorNumElements();
18194         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18195
18196         // Simple i8 add case
18197         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18198           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18199
18200         // ashr(R, 7)  === cmp_slt(R, 0)
18201         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18202           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18203           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18204         }
18205
18206         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18207         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18208           return SDValue();
18209
18210         if (Op.getOpcode() == ISD::SHL) {
18211           // Make a large shift.
18212           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18213                                                    R, ShiftAmt, DAG);
18214           SHL = DAG.getBitcast(VT, SHL);
18215           // Zero out the rightmost bits.
18216           SmallVector<SDValue, 32> V(
18217               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18218           return DAG.getNode(ISD::AND, dl, VT, SHL,
18219                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18220         }
18221         if (Op.getOpcode() == ISD::SRL) {
18222           // Make a large shift.
18223           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18224                                                    R, ShiftAmt, DAG);
18225           SRL = DAG.getBitcast(VT, SRL);
18226           // Zero out the leftmost bits.
18227           SmallVector<SDValue, 32> V(
18228               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18229           return DAG.getNode(ISD::AND, dl, VT, SRL,
18230                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18231         }
18232         if (Op.getOpcode() == ISD::SRA) {
18233           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18234           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18235           SmallVector<SDValue, 32> V(NumElts,
18236                                      DAG.getConstant(128 >> ShiftAmt, dl,
18237                                                      MVT::i8));
18238           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18239           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18240           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18241           return Res;
18242         }
18243         llvm_unreachable("Unknown shift opcode.");
18244       }
18245     }
18246   }
18247
18248   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18249   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18250       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18251
18252     // Peek through any splat that was introduced for i64 shift vectorization.
18253     int SplatIndex = -1;
18254     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18255       if (SVN->isSplat()) {
18256         SplatIndex = SVN->getSplatIndex();
18257         Amt = Amt.getOperand(0);
18258         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18259                "Splat shuffle referencing second operand");
18260       }
18261
18262     if (Amt.getOpcode() != ISD::BITCAST ||
18263         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18264       return SDValue();
18265
18266     Amt = Amt.getOperand(0);
18267     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18268                      VT.getVectorNumElements();
18269     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18270     uint64_t ShiftAmt = 0;
18271     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18272     for (unsigned i = 0; i != Ratio; ++i) {
18273       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18274       if (!C)
18275         return SDValue();
18276       // 6 == Log2(64)
18277       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18278     }
18279
18280     // Check remaining shift amounts (if not a splat).
18281     if (SplatIndex < 0) {
18282       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18283         uint64_t ShAmt = 0;
18284         for (unsigned j = 0; j != Ratio; ++j) {
18285           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18286           if (!C)
18287             return SDValue();
18288           // 6 == Log2(64)
18289           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18290         }
18291         if (ShAmt != ShiftAmt)
18292           return SDValue();
18293       }
18294     }
18295
18296     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18297       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18298
18299     if (Op.getOpcode() == ISD::SRA)
18300       return ArithmeticShiftRight64(ShiftAmt);
18301   }
18302
18303   return SDValue();
18304 }
18305
18306 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18307                                         const X86Subtarget* Subtarget) {
18308   MVT VT = Op.getSimpleValueType();
18309   SDLoc dl(Op);
18310   SDValue R = Op.getOperand(0);
18311   SDValue Amt = Op.getOperand(1);
18312
18313   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18314     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18315
18316   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18317     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18318
18319   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18320     SDValue BaseShAmt;
18321     MVT EltVT = VT.getVectorElementType();
18322
18323     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18324       // Check if this build_vector node is doing a splat.
18325       // If so, then set BaseShAmt equal to the splat value.
18326       BaseShAmt = BV->getSplatValue();
18327       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18328         BaseShAmt = SDValue();
18329     } else {
18330       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18331         Amt = Amt.getOperand(0);
18332
18333       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18334       if (SVN && SVN->isSplat()) {
18335         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18336         SDValue InVec = Amt.getOperand(0);
18337         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18338           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18339                  "Unexpected shuffle index found!");
18340           BaseShAmt = InVec.getOperand(SplatIdx);
18341         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18342            if (ConstantSDNode *C =
18343                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18344              if (C->getZExtValue() == SplatIdx)
18345                BaseShAmt = InVec.getOperand(1);
18346            }
18347         }
18348
18349         if (!BaseShAmt)
18350           // Avoid introducing an extract element from a shuffle.
18351           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18352                                   DAG.getIntPtrConstant(SplatIdx, dl));
18353       }
18354     }
18355
18356     if (BaseShAmt.getNode()) {
18357       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18358       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18359         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18360       else if (EltVT.bitsLT(MVT::i32))
18361         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18362
18363       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18364     }
18365   }
18366
18367   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18368   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18369       Amt.getOpcode() == ISD::BITCAST &&
18370       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18371     Amt = Amt.getOperand(0);
18372     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18373                      VT.getVectorNumElements();
18374     std::vector<SDValue> Vals(Ratio);
18375     for (unsigned i = 0; i != Ratio; ++i)
18376       Vals[i] = Amt.getOperand(i);
18377     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18378       for (unsigned j = 0; j != Ratio; ++j)
18379         if (Vals[j] != Amt.getOperand(i + j))
18380           return SDValue();
18381     }
18382
18383     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18384       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18385   }
18386   return SDValue();
18387 }
18388
18389 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18390                           SelectionDAG &DAG) {
18391   MVT VT = Op.getSimpleValueType();
18392   SDLoc dl(Op);
18393   SDValue R = Op.getOperand(0);
18394   SDValue Amt = Op.getOperand(1);
18395
18396   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18397   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18398
18399   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18400     return V;
18401
18402   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18403     return V;
18404
18405   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18406     return Op;
18407
18408   // XOP has 128-bit variable logical/arithmetic shifts.
18409   // +ve/-ve Amt = shift left/right.
18410   if (Subtarget->hasXOP() &&
18411       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18412        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18413     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18414       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18415       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18416     }
18417     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18418       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18419     if (Op.getOpcode() == ISD::SRA)
18420       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18421   }
18422
18423   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18424   // shifts per-lane and then shuffle the partial results back together.
18425   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18426     // Splat the shift amounts so the scalar shifts above will catch it.
18427     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18428     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18429     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18430     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18431     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18432   }
18433
18434   // i64 vector arithmetic shift can be emulated with the transform:
18435   // M = lshr(SIGN_BIT, Amt)
18436   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18437   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18438       Op.getOpcode() == ISD::SRA) {
18439     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18440     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18441     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18442     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18443     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18444     return R;
18445   }
18446
18447   // If possible, lower this packed shift into a vector multiply instead of
18448   // expanding it into a sequence of scalar shifts.
18449   // Do this only if the vector shift count is a constant build_vector.
18450   if (Op.getOpcode() == ISD::SHL &&
18451       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18452        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18453       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18454     SmallVector<SDValue, 8> Elts;
18455     MVT SVT = VT.getVectorElementType();
18456     unsigned SVTBits = SVT.getSizeInBits();
18457     APInt One(SVTBits, 1);
18458     unsigned NumElems = VT.getVectorNumElements();
18459
18460     for (unsigned i=0; i !=NumElems; ++i) {
18461       SDValue Op = Amt->getOperand(i);
18462       if (Op->getOpcode() == ISD::UNDEF) {
18463         Elts.push_back(Op);
18464         continue;
18465       }
18466
18467       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18468       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18469       uint64_t ShAmt = C.getZExtValue();
18470       if (ShAmt >= SVTBits) {
18471         Elts.push_back(DAG.getUNDEF(SVT));
18472         continue;
18473       }
18474       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18475     }
18476     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18477     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18478   }
18479
18480   // Lower SHL with variable shift amount.
18481   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18482     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18483
18484     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18485                      DAG.getConstant(0x3f800000U, dl, VT));
18486     Op = DAG.getBitcast(MVT::v4f32, Op);
18487     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18488     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18489   }
18490
18491   // If possible, lower this shift as a sequence of two shifts by
18492   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18493   // Example:
18494   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18495   //
18496   // Could be rewritten as:
18497   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18498   //
18499   // The advantage is that the two shifts from the example would be
18500   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18501   // the vector shift into four scalar shifts plus four pairs of vector
18502   // insert/extract.
18503   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18504       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18505     unsigned TargetOpcode = X86ISD::MOVSS;
18506     bool CanBeSimplified;
18507     // The splat value for the first packed shift (the 'X' from the example).
18508     SDValue Amt1 = Amt->getOperand(0);
18509     // The splat value for the second packed shift (the 'Y' from the example).
18510     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18511                                         Amt->getOperand(2);
18512
18513     // See if it is possible to replace this node with a sequence of
18514     // two shifts followed by a MOVSS/MOVSD
18515     if (VT == MVT::v4i32) {
18516       // Check if it is legal to use a MOVSS.
18517       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18518                         Amt2 == Amt->getOperand(3);
18519       if (!CanBeSimplified) {
18520         // Otherwise, check if we can still simplify this node using a MOVSD.
18521         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18522                           Amt->getOperand(2) == Amt->getOperand(3);
18523         TargetOpcode = X86ISD::MOVSD;
18524         Amt2 = Amt->getOperand(2);
18525       }
18526     } else {
18527       // Do similar checks for the case where the machine value type
18528       // is MVT::v8i16.
18529       CanBeSimplified = Amt1 == Amt->getOperand(1);
18530       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18531         CanBeSimplified = Amt2 == Amt->getOperand(i);
18532
18533       if (!CanBeSimplified) {
18534         TargetOpcode = X86ISD::MOVSD;
18535         CanBeSimplified = true;
18536         Amt2 = Amt->getOperand(4);
18537         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18538           CanBeSimplified = Amt1 == Amt->getOperand(i);
18539         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18540           CanBeSimplified = Amt2 == Amt->getOperand(j);
18541       }
18542     }
18543
18544     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18545         isa<ConstantSDNode>(Amt2)) {
18546       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18547       MVT CastVT = MVT::v4i32;
18548       SDValue Splat1 =
18549         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18550       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18551       SDValue Splat2 =
18552         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18553       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18554       if (TargetOpcode == X86ISD::MOVSD)
18555         CastVT = MVT::v2i64;
18556       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18557       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18558       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18559                                             BitCast1, DAG);
18560       return DAG.getBitcast(VT, Result);
18561     }
18562   }
18563
18564   // v4i32 Non Uniform Shifts.
18565   // If the shift amount is constant we can shift each lane using the SSE2
18566   // immediate shifts, else we need to zero-extend each lane to the lower i64
18567   // and shift using the SSE2 variable shifts.
18568   // The separate results can then be blended together.
18569   if (VT == MVT::v4i32) {
18570     unsigned Opc = Op.getOpcode();
18571     SDValue Amt0, Amt1, Amt2, Amt3;
18572     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18573       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18574       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18575       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18576       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18577     } else {
18578       // ISD::SHL is handled above but we include it here for completeness.
18579       switch (Opc) {
18580       default:
18581         llvm_unreachable("Unknown target vector shift node");
18582       case ISD::SHL:
18583         Opc = X86ISD::VSHL;
18584         break;
18585       case ISD::SRL:
18586         Opc = X86ISD::VSRL;
18587         break;
18588       case ISD::SRA:
18589         Opc = X86ISD::VSRA;
18590         break;
18591       }
18592       // The SSE2 shifts use the lower i64 as the same shift amount for
18593       // all lanes and the upper i64 is ignored. These shuffle masks
18594       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18595       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18596       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18597       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18598       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18599       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18600     }
18601
18602     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18603     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18604     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18605     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18606     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18607     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18608     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18609   }
18610
18611   if (VT == MVT::v16i8 ||
18612       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18613     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18614     unsigned ShiftOpcode = Op->getOpcode();
18615
18616     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18617       // On SSE41 targets we make use of the fact that VSELECT lowers
18618       // to PBLENDVB which selects bytes based just on the sign bit.
18619       if (Subtarget->hasSSE41()) {
18620         V0 = DAG.getBitcast(VT, V0);
18621         V1 = DAG.getBitcast(VT, V1);
18622         Sel = DAG.getBitcast(VT, Sel);
18623         return DAG.getBitcast(SelVT,
18624                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18625       }
18626       // On pre-SSE41 targets we test for the sign bit by comparing to
18627       // zero - a negative value will set all bits of the lanes to true
18628       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18629       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18630       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18631       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18632     };
18633
18634     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18635     // We can safely do this using i16 shifts as we're only interested in
18636     // the 3 lower bits of each byte.
18637     Amt = DAG.getBitcast(ExtVT, Amt);
18638     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18639     Amt = DAG.getBitcast(VT, Amt);
18640
18641     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18642       // r = VSELECT(r, shift(r, 4), a);
18643       SDValue M =
18644           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18645       R = SignBitSelect(VT, Amt, M, R);
18646
18647       // a += a
18648       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18649
18650       // r = VSELECT(r, shift(r, 2), a);
18651       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18652       R = SignBitSelect(VT, Amt, M, R);
18653
18654       // a += a
18655       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18656
18657       // return VSELECT(r, shift(r, 1), a);
18658       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18659       R = SignBitSelect(VT, Amt, M, R);
18660       return R;
18661     }
18662
18663     if (Op->getOpcode() == ISD::SRA) {
18664       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18665       // so we can correctly sign extend. We don't care what happens to the
18666       // lower byte.
18667       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18668       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18669       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18670       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18671       ALo = DAG.getBitcast(ExtVT, ALo);
18672       AHi = DAG.getBitcast(ExtVT, AHi);
18673       RLo = DAG.getBitcast(ExtVT, RLo);
18674       RHi = DAG.getBitcast(ExtVT, RHi);
18675
18676       // r = VSELECT(r, shift(r, 4), a);
18677       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18678                                 DAG.getConstant(4, dl, ExtVT));
18679       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18680                                 DAG.getConstant(4, dl, ExtVT));
18681       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18682       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18683
18684       // a += a
18685       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18686       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18687
18688       // r = VSELECT(r, shift(r, 2), a);
18689       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18690                         DAG.getConstant(2, dl, ExtVT));
18691       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18692                         DAG.getConstant(2, dl, ExtVT));
18693       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18694       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18695
18696       // a += a
18697       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18698       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18699
18700       // r = VSELECT(r, shift(r, 1), a);
18701       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18702                         DAG.getConstant(1, dl, ExtVT));
18703       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18704                         DAG.getConstant(1, dl, ExtVT));
18705       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18706       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18707
18708       // Logical shift the result back to the lower byte, leaving a zero upper
18709       // byte
18710       // meaning that we can safely pack with PACKUSWB.
18711       RLo =
18712           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18713       RHi =
18714           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18715       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18716     }
18717   }
18718
18719   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18720   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18721   // solution better.
18722   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18723     MVT ExtVT = MVT::v8i32;
18724     unsigned ExtOpc =
18725         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18726     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18727     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18728     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18729                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18730   }
18731
18732   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18733     MVT ExtVT = MVT::v8i32;
18734     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18735     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18736     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18737     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18738     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18739     ALo = DAG.getBitcast(ExtVT, ALo);
18740     AHi = DAG.getBitcast(ExtVT, AHi);
18741     RLo = DAG.getBitcast(ExtVT, RLo);
18742     RHi = DAG.getBitcast(ExtVT, RHi);
18743     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18744     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18745     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18746     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18747     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18748   }
18749
18750   if (VT == MVT::v8i16) {
18751     unsigned ShiftOpcode = Op->getOpcode();
18752
18753     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18754       // On SSE41 targets we make use of the fact that VSELECT lowers
18755       // to PBLENDVB which selects bytes based just on the sign bit.
18756       if (Subtarget->hasSSE41()) {
18757         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18758         V0 = DAG.getBitcast(ExtVT, V0);
18759         V1 = DAG.getBitcast(ExtVT, V1);
18760         Sel = DAG.getBitcast(ExtVT, Sel);
18761         return DAG.getBitcast(
18762             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18763       }
18764       // On pre-SSE41 targets we splat the sign bit - a negative value will
18765       // set all bits of the lanes to true and VSELECT uses that in
18766       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18767       SDValue C =
18768           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18769       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18770     };
18771
18772     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18773     if (Subtarget->hasSSE41()) {
18774       // On SSE41 targets we need to replicate the shift mask in both
18775       // bytes for PBLENDVB.
18776       Amt = DAG.getNode(
18777           ISD::OR, dl, VT,
18778           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18779           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18780     } else {
18781       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18782     }
18783
18784     // r = VSELECT(r, shift(r, 8), a);
18785     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18786     R = SignBitSelect(Amt, M, R);
18787
18788     // a += a
18789     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18790
18791     // r = VSELECT(r, shift(r, 4), a);
18792     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18793     R = SignBitSelect(Amt, M, R);
18794
18795     // a += a
18796     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18797
18798     // r = VSELECT(r, shift(r, 2), a);
18799     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18800     R = SignBitSelect(Amt, M, R);
18801
18802     // a += a
18803     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18804
18805     // return VSELECT(r, shift(r, 1), a);
18806     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18807     R = SignBitSelect(Amt, M, R);
18808     return R;
18809   }
18810
18811   // Decompose 256-bit shifts into smaller 128-bit shifts.
18812   if (VT.is256BitVector()) {
18813     unsigned NumElems = VT.getVectorNumElements();
18814     MVT EltVT = VT.getVectorElementType();
18815     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18816
18817     // Extract the two vectors
18818     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18819     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18820
18821     // Recreate the shift amount vectors
18822     SDValue Amt1, Amt2;
18823     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18824       // Constant shift amount
18825       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18826       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18827       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18828
18829       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18830       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18831     } else {
18832       // Variable shift amount
18833       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18834       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18835     }
18836
18837     // Issue new vector shifts for the smaller types
18838     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18839     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18840
18841     // Concatenate the result back
18842     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18843   }
18844
18845   return SDValue();
18846 }
18847
18848 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18849                            SelectionDAG &DAG) {
18850   MVT VT = Op.getSimpleValueType();
18851   SDLoc DL(Op);
18852   SDValue R = Op.getOperand(0);
18853   SDValue Amt = Op.getOperand(1);
18854
18855   assert(VT.isVector() && "Custom lowering only for vector rotates!");
18856   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18857   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18858
18859   // XOP has 128-bit vector variable + immediate rotates.
18860   // +ve/-ve Amt = rotate left/right.
18861
18862   // Split 256-bit integers.
18863   if (VT.is256BitVector())
18864     return Lower256IntArith(Op, DAG);
18865
18866   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
18867
18868   // Attempt to rotate by immediate.
18869   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18870     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18871       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18872       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18873       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18874                          DAG.getConstant(RotateAmt, DL, MVT::i8));
18875     }
18876   }
18877
18878   // Use general rotate by variable (per-element).
18879   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18880 }
18881
18882 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18883   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18884   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18885   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18886   // has only one use.
18887   SDNode *N = Op.getNode();
18888   SDValue LHS = N->getOperand(0);
18889   SDValue RHS = N->getOperand(1);
18890   unsigned BaseOp = 0;
18891   unsigned Cond = 0;
18892   SDLoc DL(Op);
18893   switch (Op.getOpcode()) {
18894   default: llvm_unreachable("Unknown ovf instruction!");
18895   case ISD::SADDO:
18896     // A subtract of one will be selected as a INC. Note that INC doesn't
18897     // set CF, so we can't do this for UADDO.
18898     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18899       if (C->isOne()) {
18900         BaseOp = X86ISD::INC;
18901         Cond = X86::COND_O;
18902         break;
18903       }
18904     BaseOp = X86ISD::ADD;
18905     Cond = X86::COND_O;
18906     break;
18907   case ISD::UADDO:
18908     BaseOp = X86ISD::ADD;
18909     Cond = X86::COND_B;
18910     break;
18911   case ISD::SSUBO:
18912     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18913     // set CF, so we can't do this for USUBO.
18914     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18915       if (C->isOne()) {
18916         BaseOp = X86ISD::DEC;
18917         Cond = X86::COND_O;
18918         break;
18919       }
18920     BaseOp = X86ISD::SUB;
18921     Cond = X86::COND_O;
18922     break;
18923   case ISD::USUBO:
18924     BaseOp = X86ISD::SUB;
18925     Cond = X86::COND_B;
18926     break;
18927   case ISD::SMULO:
18928     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18929     Cond = X86::COND_O;
18930     break;
18931   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18932     if (N->getValueType(0) == MVT::i8) {
18933       BaseOp = X86ISD::UMUL8;
18934       Cond = X86::COND_O;
18935       break;
18936     }
18937     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18938                                  MVT::i32);
18939     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18940
18941     SDValue SetCC =
18942       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18943                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18944                   SDValue(Sum.getNode(), 2));
18945
18946     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18947   }
18948   }
18949
18950   // Also sets EFLAGS.
18951   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18952   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18953
18954   SDValue SetCC =
18955     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18956                 DAG.getConstant(Cond, DL, MVT::i32),
18957                 SDValue(Sum.getNode(), 1));
18958
18959   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18960 }
18961
18962 /// Returns true if the operand type is exactly twice the native width, and
18963 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18964 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18965 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18966 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18967   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18968
18969   if (OpWidth == 64)
18970     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18971   else if (OpWidth == 128)
18972     return Subtarget->hasCmpxchg16b();
18973   else
18974     return false;
18975 }
18976
18977 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18978   return needsCmpXchgNb(SI->getValueOperand()->getType());
18979 }
18980
18981 // Note: this turns large loads into lock cmpxchg8b/16b.
18982 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18983 TargetLowering::AtomicExpansionKind
18984 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18985   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18986   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18987                                                : AtomicExpansionKind::None;
18988 }
18989
18990 TargetLowering::AtomicExpansionKind
18991 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18992   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18993   Type *MemType = AI->getType();
18994
18995   // If the operand is too big, we must see if cmpxchg8/16b is available
18996   // and default to library calls otherwise.
18997   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18998     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18999                                    : AtomicExpansionKind::None;
19000   }
19001
19002   AtomicRMWInst::BinOp Op = AI->getOperation();
19003   switch (Op) {
19004   default:
19005     llvm_unreachable("Unknown atomic operation");
19006   case AtomicRMWInst::Xchg:
19007   case AtomicRMWInst::Add:
19008   case AtomicRMWInst::Sub:
19009     // It's better to use xadd, xsub or xchg for these in all cases.
19010     return AtomicExpansionKind::None;
19011   case AtomicRMWInst::Or:
19012   case AtomicRMWInst::And:
19013   case AtomicRMWInst::Xor:
19014     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19015     // prefix to a normal instruction for these operations.
19016     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19017                             : AtomicExpansionKind::None;
19018   case AtomicRMWInst::Nand:
19019   case AtomicRMWInst::Max:
19020   case AtomicRMWInst::Min:
19021   case AtomicRMWInst::UMax:
19022   case AtomicRMWInst::UMin:
19023     // These always require a non-trivial set of data operations on x86. We must
19024     // use a cmpxchg loop.
19025     return AtomicExpansionKind::CmpXChg;
19026   }
19027 }
19028
19029 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19030   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19031   // no-sse2). There isn't any reason to disable it if the target processor
19032   // supports it.
19033   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19034 }
19035
19036 LoadInst *
19037 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19038   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19039   Type *MemType = AI->getType();
19040   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19041   // there is no benefit in turning such RMWs into loads, and it is actually
19042   // harmful as it introduces a mfence.
19043   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19044     return nullptr;
19045
19046   auto Builder = IRBuilder<>(AI);
19047   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19048   auto SynchScope = AI->getSynchScope();
19049   // We must restrict the ordering to avoid generating loads with Release or
19050   // ReleaseAcquire orderings.
19051   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19052   auto Ptr = AI->getPointerOperand();
19053
19054   // Before the load we need a fence. Here is an example lifted from
19055   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19056   // is required:
19057   // Thread 0:
19058   //   x.store(1, relaxed);
19059   //   r1 = y.fetch_add(0, release);
19060   // Thread 1:
19061   //   y.fetch_add(42, acquire);
19062   //   r2 = x.load(relaxed);
19063   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19064   // lowered to just a load without a fence. A mfence flushes the store buffer,
19065   // making the optimization clearly correct.
19066   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19067   // otherwise, we might be able to be more aggressive on relaxed idempotent
19068   // rmw. In practice, they do not look useful, so we don't try to be
19069   // especially clever.
19070   if (SynchScope == SingleThread)
19071     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19072     // the IR level, so we must wrap it in an intrinsic.
19073     return nullptr;
19074
19075   if (!hasMFENCE(*Subtarget))
19076     // FIXME: it might make sense to use a locked operation here but on a
19077     // different cache-line to prevent cache-line bouncing. In practice it
19078     // is probably a small win, and x86 processors without mfence are rare
19079     // enough that we do not bother.
19080     return nullptr;
19081
19082   Function *MFence =
19083       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19084   Builder.CreateCall(MFence, {});
19085
19086   // Finally we can emit the atomic load.
19087   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19088           AI->getType()->getPrimitiveSizeInBits());
19089   Loaded->setAtomic(Order, SynchScope);
19090   AI->replaceAllUsesWith(Loaded);
19091   AI->eraseFromParent();
19092   return Loaded;
19093 }
19094
19095 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19096                                  SelectionDAG &DAG) {
19097   SDLoc dl(Op);
19098   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19099     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19100   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19101     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19102
19103   // The only fence that needs an instruction is a sequentially-consistent
19104   // cross-thread fence.
19105   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19106     if (hasMFENCE(*Subtarget))
19107       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19108
19109     SDValue Chain = Op.getOperand(0);
19110     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19111     SDValue Ops[] = {
19112       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19113       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19114       DAG.getRegister(0, MVT::i32),            // Index
19115       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19116       DAG.getRegister(0, MVT::i32),            // Segment.
19117       Zero,
19118       Chain
19119     };
19120     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19121     return SDValue(Res, 0);
19122   }
19123
19124   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19125   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19126 }
19127
19128 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19129                              SelectionDAG &DAG) {
19130   MVT T = Op.getSimpleValueType();
19131   SDLoc DL(Op);
19132   unsigned Reg = 0;
19133   unsigned size = 0;
19134   switch(T.SimpleTy) {
19135   default: llvm_unreachable("Invalid value type!");
19136   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19137   case MVT::i16: Reg = X86::AX;  size = 2; break;
19138   case MVT::i32: Reg = X86::EAX; size = 4; break;
19139   case MVT::i64:
19140     assert(Subtarget->is64Bit() && "Node not type legal!");
19141     Reg = X86::RAX; size = 8;
19142     break;
19143   }
19144   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19145                                   Op.getOperand(2), SDValue());
19146   SDValue Ops[] = { cpIn.getValue(0),
19147                     Op.getOperand(1),
19148                     Op.getOperand(3),
19149                     DAG.getTargetConstant(size, DL, MVT::i8),
19150                     cpIn.getValue(1) };
19151   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19152   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19153   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19154                                            Ops, T, MMO);
19155
19156   SDValue cpOut =
19157     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19158   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19159                                       MVT::i32, cpOut.getValue(2));
19160   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19161                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19162                                 EFLAGS);
19163
19164   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19165   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19166   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19167   return SDValue();
19168 }
19169
19170 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19171                             SelectionDAG &DAG) {
19172   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19173   MVT DstVT = Op.getSimpleValueType();
19174
19175   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19176     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19177     if (DstVT != MVT::f64)
19178       // This conversion needs to be expanded.
19179       return SDValue();
19180
19181     SDValue InVec = Op->getOperand(0);
19182     SDLoc dl(Op);
19183     unsigned NumElts = SrcVT.getVectorNumElements();
19184     MVT SVT = SrcVT.getVectorElementType();
19185
19186     // Widen the vector in input in the case of MVT::v2i32.
19187     // Example: from MVT::v2i32 to MVT::v4i32.
19188     SmallVector<SDValue, 16> Elts;
19189     for (unsigned i = 0, e = NumElts; i != e; ++i)
19190       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19191                                  DAG.getIntPtrConstant(i, dl)));
19192
19193     // Explicitly mark the extra elements as Undef.
19194     Elts.append(NumElts, DAG.getUNDEF(SVT));
19195
19196     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19197     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19198     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19199     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19200                        DAG.getIntPtrConstant(0, dl));
19201   }
19202
19203   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19204          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19205   assert((DstVT == MVT::i64 ||
19206           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19207          "Unexpected custom BITCAST");
19208   // i64 <=> MMX conversions are Legal.
19209   if (SrcVT==MVT::i64 && DstVT.isVector())
19210     return Op;
19211   if (DstVT==MVT::i64 && SrcVT.isVector())
19212     return Op;
19213   // MMX <=> MMX conversions are Legal.
19214   if (SrcVT.isVector() && DstVT.isVector())
19215     return Op;
19216   // All other conversions need to be expanded.
19217   return SDValue();
19218 }
19219
19220 /// Compute the horizontal sum of bytes in V for the elements of VT.
19221 ///
19222 /// Requires V to be a byte vector and VT to be an integer vector type with
19223 /// wider elements than V's type. The width of the elements of VT determines
19224 /// how many bytes of V are summed horizontally to produce each element of the
19225 /// result.
19226 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19227                                       const X86Subtarget *Subtarget,
19228                                       SelectionDAG &DAG) {
19229   SDLoc DL(V);
19230   MVT ByteVecVT = V.getSimpleValueType();
19231   MVT EltVT = VT.getVectorElementType();
19232   int NumElts = VT.getVectorNumElements();
19233   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19234          "Expected value to have byte element type.");
19235   assert(EltVT != MVT::i8 &&
19236          "Horizontal byte sum only makes sense for wider elements!");
19237   unsigned VecSize = VT.getSizeInBits();
19238   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19239
19240   // PSADBW instruction horizontally add all bytes and leave the result in i64
19241   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19242   if (EltVT == MVT::i64) {
19243     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19244     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19245     return DAG.getBitcast(VT, V);
19246   }
19247
19248   if (EltVT == MVT::i32) {
19249     // We unpack the low half and high half into i32s interleaved with zeros so
19250     // that we can use PSADBW to horizontally sum them. The most useful part of
19251     // this is that it lines up the results of two PSADBW instructions to be
19252     // two v2i64 vectors which concatenated are the 4 population counts. We can
19253     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19254     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19255     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19256     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19257
19258     // Do the horizontal sums into two v2i64s.
19259     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19260     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19261                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19262     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19263                        DAG.getBitcast(ByteVecVT, High), Zeros);
19264
19265     // Merge them together.
19266     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19267     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19268                     DAG.getBitcast(ShortVecVT, Low),
19269                     DAG.getBitcast(ShortVecVT, High));
19270
19271     return DAG.getBitcast(VT, V);
19272   }
19273
19274   // The only element type left is i16.
19275   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19276
19277   // To obtain pop count for each i16 element starting from the pop count for
19278   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19279   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19280   // directly supported.
19281   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19282   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19283   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19284   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19285                   DAG.getBitcast(ByteVecVT, V));
19286   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19287 }
19288
19289 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19290                                         const X86Subtarget *Subtarget,
19291                                         SelectionDAG &DAG) {
19292   MVT VT = Op.getSimpleValueType();
19293   MVT EltVT = VT.getVectorElementType();
19294   unsigned VecSize = VT.getSizeInBits();
19295
19296   // Implement a lookup table in register by using an algorithm based on:
19297   // http://wm.ite.pl/articles/sse-popcount.html
19298   //
19299   // The general idea is that every lower byte nibble in the input vector is an
19300   // index into a in-register pre-computed pop count table. We then split up the
19301   // input vector in two new ones: (1) a vector with only the shifted-right
19302   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19303   // masked out higher ones) for each byte. PSHUB is used separately with both
19304   // to index the in-register table. Next, both are added and the result is a
19305   // i8 vector where each element contains the pop count for input byte.
19306   //
19307   // To obtain the pop count for elements != i8, we follow up with the same
19308   // approach and use additional tricks as described below.
19309   //
19310   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19311                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19312                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19313                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19314
19315   int NumByteElts = VecSize / 8;
19316   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19317   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19318   SmallVector<SDValue, 16> LUTVec;
19319   for (int i = 0; i < NumByteElts; ++i)
19320     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19321   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19322   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19323                                   DAG.getConstant(0x0F, DL, MVT::i8));
19324   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19325
19326   // High nibbles
19327   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19328   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19329   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19330
19331   // Low nibbles
19332   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19333
19334   // The input vector is used as the shuffle mask that index elements into the
19335   // LUT. After counting low and high nibbles, add the vector to obtain the
19336   // final pop count per i8 element.
19337   SDValue HighPopCnt =
19338       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19339   SDValue LowPopCnt =
19340       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19341   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19342
19343   if (EltVT == MVT::i8)
19344     return PopCnt;
19345
19346   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19347 }
19348
19349 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19350                                        const X86Subtarget *Subtarget,
19351                                        SelectionDAG &DAG) {
19352   MVT VT = Op.getSimpleValueType();
19353   assert(VT.is128BitVector() &&
19354          "Only 128-bit vector bitmath lowering supported.");
19355
19356   int VecSize = VT.getSizeInBits();
19357   MVT EltVT = VT.getVectorElementType();
19358   int Len = EltVT.getSizeInBits();
19359
19360   // This is the vectorized version of the "best" algorithm from
19361   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19362   // with a minor tweak to use a series of adds + shifts instead of vector
19363   // multiplications. Implemented for all integer vector types. We only use
19364   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19365   // much faster, even faster than using native popcnt instructions.
19366
19367   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19368     MVT VT = V.getSimpleValueType();
19369     SmallVector<SDValue, 32> Shifters(
19370         VT.getVectorNumElements(),
19371         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19372     return DAG.getNode(OpCode, DL, VT, V,
19373                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19374   };
19375   auto GetMask = [&](SDValue V, APInt Mask) {
19376     MVT VT = V.getSimpleValueType();
19377     SmallVector<SDValue, 32> Masks(
19378         VT.getVectorNumElements(),
19379         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19380     return DAG.getNode(ISD::AND, DL, VT, V,
19381                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19382   };
19383
19384   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19385   // x86, so set the SRL type to have elements at least i16 wide. This is
19386   // correct because all of our SRLs are followed immediately by a mask anyways
19387   // that handles any bits that sneak into the high bits of the byte elements.
19388   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19389
19390   SDValue V = Op;
19391
19392   // v = v - ((v >> 1) & 0x55555555...)
19393   SDValue Srl =
19394       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19395   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19396   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19397
19398   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19399   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19400   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19401   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19402   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19403
19404   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19405   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19406   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19407   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19408
19409   // At this point, V contains the byte-wise population count, and we are
19410   // merely doing a horizontal sum if necessary to get the wider element
19411   // counts.
19412   if (EltVT == MVT::i8)
19413     return V;
19414
19415   return LowerHorizontalByteSum(
19416       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19417       DAG);
19418 }
19419
19420 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19421                                 SelectionDAG &DAG) {
19422   MVT VT = Op.getSimpleValueType();
19423   // FIXME: Need to add AVX-512 support here!
19424   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19425          "Unknown CTPOP type to handle");
19426   SDLoc DL(Op.getNode());
19427   SDValue Op0 = Op.getOperand(0);
19428
19429   if (!Subtarget->hasSSSE3()) {
19430     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19431     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19432     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19433   }
19434
19435   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19436     unsigned NumElems = VT.getVectorNumElements();
19437
19438     // Extract each 128-bit vector, compute pop count and concat the result.
19439     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19440     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19441
19442     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19443                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19444                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19445   }
19446
19447   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19448 }
19449
19450 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19451                           SelectionDAG &DAG) {
19452   assert(Op.getSimpleValueType().isVector() &&
19453          "We only do custom lowering for vector population count.");
19454   return LowerVectorCTPOP(Op, Subtarget, DAG);
19455 }
19456
19457 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19458   SDNode *Node = Op.getNode();
19459   SDLoc dl(Node);
19460   EVT T = Node->getValueType(0);
19461   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19462                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19463   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19464                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19465                        Node->getOperand(0),
19466                        Node->getOperand(1), negOp,
19467                        cast<AtomicSDNode>(Node)->getMemOperand(),
19468                        cast<AtomicSDNode>(Node)->getOrdering(),
19469                        cast<AtomicSDNode>(Node)->getSynchScope());
19470 }
19471
19472 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19473   SDNode *Node = Op.getNode();
19474   SDLoc dl(Node);
19475   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19476
19477   // Convert seq_cst store -> xchg
19478   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19479   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19480   //        (The only way to get a 16-byte store is cmpxchg16b)
19481   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19482   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19483       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19484     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19485                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19486                                  Node->getOperand(0),
19487                                  Node->getOperand(1), Node->getOperand(2),
19488                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19489                                  cast<AtomicSDNode>(Node)->getOrdering(),
19490                                  cast<AtomicSDNode>(Node)->getSynchScope());
19491     return Swap.getValue(1);
19492   }
19493   // Other atomic stores have a simple pattern.
19494   return Op;
19495 }
19496
19497 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19498   MVT VT = Op.getNode()->getSimpleValueType(0);
19499
19500   // Let legalize expand this if it isn't a legal type yet.
19501   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19502     return SDValue();
19503
19504   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19505
19506   unsigned Opc;
19507   bool ExtraOp = false;
19508   switch (Op.getOpcode()) {
19509   default: llvm_unreachable("Invalid code");
19510   case ISD::ADDC: Opc = X86ISD::ADD; break;
19511   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19512   case ISD::SUBC: Opc = X86ISD::SUB; break;
19513   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19514   }
19515
19516   if (!ExtraOp)
19517     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19518                        Op.getOperand(1));
19519   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19520                      Op.getOperand(1), Op.getOperand(2));
19521 }
19522
19523 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19524                             SelectionDAG &DAG) {
19525   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19526
19527   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19528   // which returns the values as { float, float } (in XMM0) or
19529   // { double, double } (which is returned in XMM0, XMM1).
19530   SDLoc dl(Op);
19531   SDValue Arg = Op.getOperand(0);
19532   EVT ArgVT = Arg.getValueType();
19533   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19534
19535   TargetLowering::ArgListTy Args;
19536   TargetLowering::ArgListEntry Entry;
19537
19538   Entry.Node = Arg;
19539   Entry.Ty = ArgTy;
19540   Entry.isSExt = false;
19541   Entry.isZExt = false;
19542   Args.push_back(Entry);
19543
19544   bool isF64 = ArgVT == MVT::f64;
19545   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19546   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19547   // the results are returned via SRet in memory.
19548   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19550   SDValue Callee =
19551       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19552
19553   Type *RetTy = isF64
19554     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19555     : (Type*)VectorType::get(ArgTy, 4);
19556
19557   TargetLowering::CallLoweringInfo CLI(DAG);
19558   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19559     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19560
19561   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19562
19563   if (isF64)
19564     // Returned in xmm0 and xmm1.
19565     return CallResult.first;
19566
19567   // Returned in bits 0:31 and 32:64 xmm0.
19568   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19569                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19570   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19571                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19572   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19573   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19574 }
19575
19576 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19577                              SelectionDAG &DAG) {
19578   assert(Subtarget->hasAVX512() &&
19579          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19580
19581   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19582   MVT VT = N->getValue().getSimpleValueType();
19583   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19584   SDLoc dl(Op);
19585
19586   // X86 scatter kills mask register, so its type should be added to
19587   // the list of return values
19588   if (N->getNumValues() == 1) {
19589     SDValue Index = N->getIndex();
19590     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19591         !Index.getSimpleValueType().is512BitVector())
19592       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19593
19594     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19595     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19596                       N->getOperand(3), Index };
19597
19598     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19599     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19600     return SDValue(NewScatter.getNode(), 0);
19601   }
19602   return Op;
19603 }
19604
19605 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19606                             SelectionDAG &DAG) {
19607   assert(Subtarget->hasAVX512() &&
19608          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19609
19610   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19611   MVT VT = Op.getSimpleValueType();
19612   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19613   SDLoc dl(Op);
19614
19615   SDValue Index = N->getIndex();
19616   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19617       !Index.getSimpleValueType().is512BitVector()) {
19618     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19619     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19620                       N->getOperand(3), Index };
19621     DAG.UpdateNodeOperands(N, Ops);
19622   }
19623   return Op;
19624 }
19625
19626 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19627                                                     SelectionDAG &DAG) const {
19628   // TODO: Eventually, the lowering of these nodes should be informed by or
19629   // deferred to the GC strategy for the function in which they appear. For
19630   // now, however, they must be lowered to something. Since they are logically
19631   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19632   // require special handling for these nodes), lower them as literal NOOPs for
19633   // the time being.
19634   SmallVector<SDValue, 2> Ops;
19635
19636   Ops.push_back(Op.getOperand(0));
19637   if (Op->getGluedNode())
19638     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19639
19640   SDLoc OpDL(Op);
19641   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19642   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19643
19644   return NOOP;
19645 }
19646
19647 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19648                                                   SelectionDAG &DAG) const {
19649   // TODO: Eventually, the lowering of these nodes should be informed by or
19650   // deferred to the GC strategy for the function in which they appear. For
19651   // now, however, they must be lowered to something. Since they are logically
19652   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19653   // require special handling for these nodes), lower them as literal NOOPs for
19654   // the time being.
19655   SmallVector<SDValue, 2> Ops;
19656
19657   Ops.push_back(Op.getOperand(0));
19658   if (Op->getGluedNode())
19659     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19660
19661   SDLoc OpDL(Op);
19662   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19663   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19664
19665   return NOOP;
19666 }
19667
19668 /// LowerOperation - Provide custom lowering hooks for some operations.
19669 ///
19670 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19671   switch (Op.getOpcode()) {
19672   default: llvm_unreachable("Should not custom lower this!");
19673   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19674   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19675     return LowerCMP_SWAP(Op, Subtarget, DAG);
19676   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19677   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19678   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19679   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19680   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19681   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19682   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19683   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19684   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19685   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19686   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19687   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19688   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19689   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19690   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19691   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19692   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19693   case ISD::SHL_PARTS:
19694   case ISD::SRA_PARTS:
19695   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19696   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19697   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19698   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19699   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19700   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19701   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19702   case ISD::SIGN_EXTEND_VECTOR_INREG:
19703     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19704   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19705   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19706   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19707   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19708   case ISD::FABS:
19709   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19710   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19711   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19712   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19713   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
19714   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19715   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19716   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19717   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19718   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19719   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19720   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19721   case ISD::INTRINSIC_VOID:
19722   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19723   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19724   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19725   case ISD::FRAME_TO_ARGS_OFFSET:
19726                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19727   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19728   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19729   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19730   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19731   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19732   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19733   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19734   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
19735   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19736   case ISD::CTTZ:
19737   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19738   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19739   case ISD::UMUL_LOHI:
19740   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19741   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
19742   case ISD::SRA:
19743   case ISD::SRL:
19744   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19745   case ISD::SADDO:
19746   case ISD::UADDO:
19747   case ISD::SSUBO:
19748   case ISD::USUBO:
19749   case ISD::SMULO:
19750   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19751   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19752   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19753   case ISD::ADDC:
19754   case ISD::ADDE:
19755   case ISD::SUBC:
19756   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19757   case ISD::ADD:                return LowerADD(Op, DAG);
19758   case ISD::SUB:                return LowerSUB(Op, DAG);
19759   case ISD::SMAX:
19760   case ISD::SMIN:
19761   case ISD::UMAX:
19762   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19763   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19764   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19765   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19766   case ISD::GC_TRANSITION_START:
19767                                 return LowerGC_TRANSITION_START(Op, DAG);
19768   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19769   }
19770 }
19771
19772 /// ReplaceNodeResults - Replace a node with an illegal result type
19773 /// with a new node built out of custom code.
19774 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19775                                            SmallVectorImpl<SDValue>&Results,
19776                                            SelectionDAG &DAG) const {
19777   SDLoc dl(N);
19778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19779   switch (N->getOpcode()) {
19780   default:
19781     llvm_unreachable("Do not know how to custom type legalize this operation!");
19782   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19783   case X86ISD::FMINC:
19784   case X86ISD::FMIN:
19785   case X86ISD::FMAXC:
19786   case X86ISD::FMAX: {
19787     EVT VT = N->getValueType(0);
19788     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
19789     SDValue UNDEF = DAG.getUNDEF(VT);
19790     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19791                               N->getOperand(0), UNDEF);
19792     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19793                               N->getOperand(1), UNDEF);
19794     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19795     return;
19796   }
19797   case ISD::SIGN_EXTEND_INREG:
19798   case ISD::ADDC:
19799   case ISD::ADDE:
19800   case ISD::SUBC:
19801   case ISD::SUBE:
19802     // We don't want to expand or promote these.
19803     return;
19804   case ISD::SDIV:
19805   case ISD::UDIV:
19806   case ISD::SREM:
19807   case ISD::UREM:
19808   case ISD::SDIVREM:
19809   case ISD::UDIVREM: {
19810     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19811     Results.push_back(V);
19812     return;
19813   }
19814   case ISD::FP_TO_SINT:
19815   case ISD::FP_TO_UINT: {
19816     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19817
19818     std::pair<SDValue,SDValue> Vals =
19819         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19820     SDValue FIST = Vals.first, StackSlot = Vals.second;
19821     if (FIST.getNode()) {
19822       EVT VT = N->getValueType(0);
19823       // Return a load from the stack slot.
19824       if (StackSlot.getNode())
19825         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19826                                       MachinePointerInfo(),
19827                                       false, false, false, 0));
19828       else
19829         Results.push_back(FIST);
19830     }
19831     return;
19832   }
19833   case ISD::UINT_TO_FP: {
19834     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19835     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19836         N->getValueType(0) != MVT::v2f32)
19837       return;
19838     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19839                                  N->getOperand(0));
19840     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19841                                      MVT::f64);
19842     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19843     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19844                              DAG.getBitcast(MVT::v2i64, VBias));
19845     Or = DAG.getBitcast(MVT::v2f64, Or);
19846     // TODO: Are there any fast-math-flags to propagate here?
19847     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19848     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19849     return;
19850   }
19851   case ISD::FP_ROUND: {
19852     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19853         return;
19854     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19855     Results.push_back(V);
19856     return;
19857   }
19858   case ISD::FP_EXTEND: {
19859     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19860     // No other ValueType for FP_EXTEND should reach this point.
19861     assert(N->getValueType(0) == MVT::v2f32 &&
19862            "Do not know how to legalize this Node");
19863     return;
19864   }
19865   case ISD::INTRINSIC_W_CHAIN: {
19866     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19867     switch (IntNo) {
19868     default : llvm_unreachable("Do not know how to custom type "
19869                                "legalize this intrinsic operation!");
19870     case Intrinsic::x86_rdtsc:
19871       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19872                                      Results);
19873     case Intrinsic::x86_rdtscp:
19874       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19875                                      Results);
19876     case Intrinsic::x86_rdpmc:
19877       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19878     }
19879   }
19880   case ISD::READCYCLECOUNTER: {
19881     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19882                                    Results);
19883   }
19884   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19885     EVT T = N->getValueType(0);
19886     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19887     bool Regs64bit = T == MVT::i128;
19888     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19889     SDValue cpInL, cpInH;
19890     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19891                         DAG.getConstant(0, dl, HalfT));
19892     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19893                         DAG.getConstant(1, dl, HalfT));
19894     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19895                              Regs64bit ? X86::RAX : X86::EAX,
19896                              cpInL, SDValue());
19897     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19898                              Regs64bit ? X86::RDX : X86::EDX,
19899                              cpInH, cpInL.getValue(1));
19900     SDValue swapInL, swapInH;
19901     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19902                           DAG.getConstant(0, dl, HalfT));
19903     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19904                           DAG.getConstant(1, dl, HalfT));
19905     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19906                                Regs64bit ? X86::RBX : X86::EBX,
19907                                swapInL, cpInH.getValue(1));
19908     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19909                                Regs64bit ? X86::RCX : X86::ECX,
19910                                swapInH, swapInL.getValue(1));
19911     SDValue Ops[] = { swapInH.getValue(0),
19912                       N->getOperand(1),
19913                       swapInH.getValue(1) };
19914     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19915     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19916     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19917                                   X86ISD::LCMPXCHG8_DAG;
19918     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19919     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19920                                         Regs64bit ? X86::RAX : X86::EAX,
19921                                         HalfT, Result.getValue(1));
19922     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19923                                         Regs64bit ? X86::RDX : X86::EDX,
19924                                         HalfT, cpOutL.getValue(2));
19925     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19926
19927     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19928                                         MVT::i32, cpOutH.getValue(2));
19929     SDValue Success =
19930         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19931                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19932     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19933
19934     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19935     Results.push_back(Success);
19936     Results.push_back(EFLAGS.getValue(1));
19937     return;
19938   }
19939   case ISD::ATOMIC_SWAP:
19940   case ISD::ATOMIC_LOAD_ADD:
19941   case ISD::ATOMIC_LOAD_SUB:
19942   case ISD::ATOMIC_LOAD_AND:
19943   case ISD::ATOMIC_LOAD_OR:
19944   case ISD::ATOMIC_LOAD_XOR:
19945   case ISD::ATOMIC_LOAD_NAND:
19946   case ISD::ATOMIC_LOAD_MIN:
19947   case ISD::ATOMIC_LOAD_MAX:
19948   case ISD::ATOMIC_LOAD_UMIN:
19949   case ISD::ATOMIC_LOAD_UMAX:
19950   case ISD::ATOMIC_LOAD: {
19951     // Delegate to generic TypeLegalization. Situations we can really handle
19952     // should have already been dealt with by AtomicExpandPass.cpp.
19953     break;
19954   }
19955   case ISD::BITCAST: {
19956     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19957     EVT DstVT = N->getValueType(0);
19958     EVT SrcVT = N->getOperand(0)->getValueType(0);
19959
19960     if (SrcVT != MVT::f64 ||
19961         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19962       return;
19963
19964     unsigned NumElts = DstVT.getVectorNumElements();
19965     EVT SVT = DstVT.getVectorElementType();
19966     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19967     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19968                                    MVT::v2f64, N->getOperand(0));
19969     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19970
19971     if (ExperimentalVectorWideningLegalization) {
19972       // If we are legalizing vectors by widening, we already have the desired
19973       // legal vector type, just return it.
19974       Results.push_back(ToVecInt);
19975       return;
19976     }
19977
19978     SmallVector<SDValue, 8> Elts;
19979     for (unsigned i = 0, e = NumElts; i != e; ++i)
19980       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19981                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19982
19983     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19984   }
19985   }
19986 }
19987
19988 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19989   switch ((X86ISD::NodeType)Opcode) {
19990   case X86ISD::FIRST_NUMBER:       break;
19991   case X86ISD::BSF:                return "X86ISD::BSF";
19992   case X86ISD::BSR:                return "X86ISD::BSR";
19993   case X86ISD::SHLD:               return "X86ISD::SHLD";
19994   case X86ISD::SHRD:               return "X86ISD::SHRD";
19995   case X86ISD::FAND:               return "X86ISD::FAND";
19996   case X86ISD::FANDN:              return "X86ISD::FANDN";
19997   case X86ISD::FOR:                return "X86ISD::FOR";
19998   case X86ISD::FXOR:               return "X86ISD::FXOR";
19999   case X86ISD::FILD:               return "X86ISD::FILD";
20000   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20001   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20002   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20003   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20004   case X86ISD::FLD:                return "X86ISD::FLD";
20005   case X86ISD::FST:                return "X86ISD::FST";
20006   case X86ISD::CALL:               return "X86ISD::CALL";
20007   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20008   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20009   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20010   case X86ISD::BT:                 return "X86ISD::BT";
20011   case X86ISD::CMP:                return "X86ISD::CMP";
20012   case X86ISD::COMI:               return "X86ISD::COMI";
20013   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20014   case X86ISD::CMPM:               return "X86ISD::CMPM";
20015   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20016   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20017   case X86ISD::SETCC:              return "X86ISD::SETCC";
20018   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20019   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20020   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20021   case X86ISD::CMOV:               return "X86ISD::CMOV";
20022   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20023   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20024   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20025   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20026   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20027   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20028   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20029   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20030   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20031   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20032   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20033   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20034   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20035   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20036   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20037   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20038   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20039   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20040   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20041   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20042   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20043   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20044   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20045   case X86ISD::HADD:               return "X86ISD::HADD";
20046   case X86ISD::HSUB:               return "X86ISD::HSUB";
20047   case X86ISD::FHADD:              return "X86ISD::FHADD";
20048   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20049   case X86ISD::ABS:                return "X86ISD::ABS";
20050   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20051   case X86ISD::FMAX:               return "X86ISD::FMAX";
20052   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20053   case X86ISD::FMIN:               return "X86ISD::FMIN";
20054   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20055   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20056   case X86ISD::FMINC:              return "X86ISD::FMINC";
20057   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20058   case X86ISD::FRCP:               return "X86ISD::FRCP";
20059   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20060   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20061   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20062   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20063   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20064   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20065   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20066   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20067   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20068   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20069   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20070   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20071   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20072   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20073   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20074   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20075   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20076   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20077   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20078   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20079   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20080   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20081   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20082   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20083   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20084   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20085   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20086   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20087   case X86ISD::VSHL:               return "X86ISD::VSHL";
20088   case X86ISD::VSRL:               return "X86ISD::VSRL";
20089   case X86ISD::VSRA:               return "X86ISD::VSRA";
20090   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20091   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20092   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20093   case X86ISD::CMPP:               return "X86ISD::CMPP";
20094   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20095   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20096   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20097   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20098   case X86ISD::ADD:                return "X86ISD::ADD";
20099   case X86ISD::SUB:                return "X86ISD::SUB";
20100   case X86ISD::ADC:                return "X86ISD::ADC";
20101   case X86ISD::SBB:                return "X86ISD::SBB";
20102   case X86ISD::SMUL:               return "X86ISD::SMUL";
20103   case X86ISD::UMUL:               return "X86ISD::UMUL";
20104   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20105   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20106   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20107   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20108   case X86ISD::INC:                return "X86ISD::INC";
20109   case X86ISD::DEC:                return "X86ISD::DEC";
20110   case X86ISD::OR:                 return "X86ISD::OR";
20111   case X86ISD::XOR:                return "X86ISD::XOR";
20112   case X86ISD::AND:                return "X86ISD::AND";
20113   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20114   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20115   case X86ISD::PTEST:              return "X86ISD::PTEST";
20116   case X86ISD::TESTP:              return "X86ISD::TESTP";
20117   case X86ISD::TESTM:              return "X86ISD::TESTM";
20118   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20119   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20120   case X86ISD::KTEST:              return "X86ISD::KTEST";
20121   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20122   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20123   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20124   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20125   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20126   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20127   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20128   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20129   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20130   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20131   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20132   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20133   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20134   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20135   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20136   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20137   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20138   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20139   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20140   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20141   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20142   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20143   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20144   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20145   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20146   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20147   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20148   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20149   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20150   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20151   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20152   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20153   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20154   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20155   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20156   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20157   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20158   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20159   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20160   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20161   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20162   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20163   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20164   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20165   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20166   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20167   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20168   case X86ISD::SAHF:               return "X86ISD::SAHF";
20169   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20170   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20171   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20172   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20173   case X86ISD::VPROT:              return "X86ISD::VPROT";
20174   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20175   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20176   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20177   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20178   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20179   case X86ISD::FMADD:              return "X86ISD::FMADD";
20180   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20181   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20182   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20183   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20184   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20185   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20186   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20187   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20188   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20189   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20190   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20191   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20192   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20193   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20194   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20195   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20196   case X86ISD::XTEST:              return "X86ISD::XTEST";
20197   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20198   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20199   case X86ISD::SELECT:             return "X86ISD::SELECT";
20200   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20201   case X86ISD::RCP28:              return "X86ISD::RCP28";
20202   case X86ISD::EXP2:               return "X86ISD::EXP2";
20203   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20204   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20205   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20206   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20207   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20208   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20209   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20210   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20211   case X86ISD::ADDS:               return "X86ISD::ADDS";
20212   case X86ISD::SUBS:               return "X86ISD::SUBS";
20213   case X86ISD::AVG:                return "X86ISD::AVG";
20214   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20215   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20216   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20217   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20218   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20219   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20220   }
20221   return nullptr;
20222 }
20223
20224 // isLegalAddressingMode - Return true if the addressing mode represented
20225 // by AM is legal for this target, for a load/store of the specified type.
20226 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20227                                               const AddrMode &AM, Type *Ty,
20228                                               unsigned AS) const {
20229   // X86 supports extremely general addressing modes.
20230   CodeModel::Model M = getTargetMachine().getCodeModel();
20231   Reloc::Model R = getTargetMachine().getRelocationModel();
20232
20233   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20234   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20235     return false;
20236
20237   if (AM.BaseGV) {
20238     unsigned GVFlags =
20239       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20240
20241     // If a reference to this global requires an extra load, we can't fold it.
20242     if (isGlobalStubReference(GVFlags))
20243       return false;
20244
20245     // If BaseGV requires a register for the PIC base, we cannot also have a
20246     // BaseReg specified.
20247     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20248       return false;
20249
20250     // If lower 4G is not available, then we must use rip-relative addressing.
20251     if ((M != CodeModel::Small || R != Reloc::Static) &&
20252         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20253       return false;
20254   }
20255
20256   switch (AM.Scale) {
20257   case 0:
20258   case 1:
20259   case 2:
20260   case 4:
20261   case 8:
20262     // These scales always work.
20263     break;
20264   case 3:
20265   case 5:
20266   case 9:
20267     // These scales are formed with basereg+scalereg.  Only accept if there is
20268     // no basereg yet.
20269     if (AM.HasBaseReg)
20270       return false;
20271     break;
20272   default:  // Other stuff never works.
20273     return false;
20274   }
20275
20276   return true;
20277 }
20278
20279 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20280   unsigned Bits = Ty->getScalarSizeInBits();
20281
20282   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20283   // particularly cheaper than those without.
20284   if (Bits == 8)
20285     return false;
20286
20287   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20288   // variable shifts just as cheap as scalar ones.
20289   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20290     return false;
20291
20292   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20293   // fully general vector.
20294   return true;
20295 }
20296
20297 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20298   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20299     return false;
20300   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20301   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20302   return NumBits1 > NumBits2;
20303 }
20304
20305 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20306   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20307     return false;
20308
20309   if (!isTypeLegal(EVT::getEVT(Ty1)))
20310     return false;
20311
20312   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20313
20314   // Assuming the caller doesn't have a zeroext or signext return parameter,
20315   // truncation all the way down to i1 is valid.
20316   return true;
20317 }
20318
20319 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20320   return isInt<32>(Imm);
20321 }
20322
20323 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20324   // Can also use sub to handle negated immediates.
20325   return isInt<32>(Imm);
20326 }
20327
20328 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20329   if (!VT1.isInteger() || !VT2.isInteger())
20330     return false;
20331   unsigned NumBits1 = VT1.getSizeInBits();
20332   unsigned NumBits2 = VT2.getSizeInBits();
20333   return NumBits1 > NumBits2;
20334 }
20335
20336 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20337   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20338   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20339 }
20340
20341 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20342   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20343   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20344 }
20345
20346 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20347   EVT VT1 = Val.getValueType();
20348   if (isZExtFree(VT1, VT2))
20349     return true;
20350
20351   if (Val.getOpcode() != ISD::LOAD)
20352     return false;
20353
20354   if (!VT1.isSimple() || !VT1.isInteger() ||
20355       !VT2.isSimple() || !VT2.isInteger())
20356     return false;
20357
20358   switch (VT1.getSimpleVT().SimpleTy) {
20359   default: break;
20360   case MVT::i8:
20361   case MVT::i16:
20362   case MVT::i32:
20363     // X86 has 8, 16, and 32-bit zero-extending loads.
20364     return true;
20365   }
20366
20367   return false;
20368 }
20369
20370 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20371
20372 bool
20373 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20374   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20375     return false;
20376
20377   VT = VT.getScalarType();
20378
20379   if (!VT.isSimple())
20380     return false;
20381
20382   switch (VT.getSimpleVT().SimpleTy) {
20383   case MVT::f32:
20384   case MVT::f64:
20385     return true;
20386   default:
20387     break;
20388   }
20389
20390   return false;
20391 }
20392
20393 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20394   // i16 instructions are longer (0x66 prefix) and potentially slower.
20395   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20396 }
20397
20398 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20399 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20400 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20401 /// are assumed to be legal.
20402 bool
20403 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20404                                       EVT VT) const {
20405   if (!VT.isSimple())
20406     return false;
20407
20408   // Not for i1 vectors
20409   if (VT.getSimpleVT().getScalarType() == MVT::i1)
20410     return false;
20411
20412   // Very little shuffling can be done for 64-bit vectors right now.
20413   if (VT.getSimpleVT().getSizeInBits() == 64)
20414     return false;
20415
20416   // We only care that the types being shuffled are legal. The lowering can
20417   // handle any possible shuffle mask that results.
20418   return isTypeLegal(VT.getSimpleVT());
20419 }
20420
20421 bool
20422 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20423                                           EVT VT) const {
20424   // Just delegate to the generic legality, clear masks aren't special.
20425   return isShuffleMaskLegal(Mask, VT);
20426 }
20427
20428 //===----------------------------------------------------------------------===//
20429 //                           X86 Scheduler Hooks
20430 //===----------------------------------------------------------------------===//
20431
20432 /// Utility function to emit xbegin specifying the start of an RTM region.
20433 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20434                                      const TargetInstrInfo *TII) {
20435   DebugLoc DL = MI->getDebugLoc();
20436
20437   const BasicBlock *BB = MBB->getBasicBlock();
20438   MachineFunction::iterator I = ++MBB->getIterator();
20439
20440   // For the v = xbegin(), we generate
20441   //
20442   // thisMBB:
20443   //  xbegin sinkMBB
20444   //
20445   // mainMBB:
20446   //  eax = -1
20447   //
20448   // sinkMBB:
20449   //  v = eax
20450
20451   MachineBasicBlock *thisMBB = MBB;
20452   MachineFunction *MF = MBB->getParent();
20453   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20454   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20455   MF->insert(I, mainMBB);
20456   MF->insert(I, sinkMBB);
20457
20458   // Transfer the remainder of BB and its successor edges to sinkMBB.
20459   sinkMBB->splice(sinkMBB->begin(), MBB,
20460                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20461   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20462
20463   // thisMBB:
20464   //  xbegin sinkMBB
20465   //  # fallthrough to mainMBB
20466   //  # abortion to sinkMBB
20467   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20468   thisMBB->addSuccessor(mainMBB);
20469   thisMBB->addSuccessor(sinkMBB);
20470
20471   // mainMBB:
20472   //  EAX = -1
20473   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20474   mainMBB->addSuccessor(sinkMBB);
20475
20476   // sinkMBB:
20477   // EAX is live into the sinkMBB
20478   sinkMBB->addLiveIn(X86::EAX);
20479   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20480           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20481     .addReg(X86::EAX);
20482
20483   MI->eraseFromParent();
20484   return sinkMBB;
20485 }
20486
20487 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20488 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20489 // in the .td file.
20490 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20491                                        const TargetInstrInfo *TII) {
20492   unsigned Opc;
20493   switch (MI->getOpcode()) {
20494   default: llvm_unreachable("illegal opcode!");
20495   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20496   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20497   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20498   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20499   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20500   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20501   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20502   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20503   }
20504
20505   DebugLoc dl = MI->getDebugLoc();
20506   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20507
20508   unsigned NumArgs = MI->getNumOperands();
20509   for (unsigned i = 1; i < NumArgs; ++i) {
20510     MachineOperand &Op = MI->getOperand(i);
20511     if (!(Op.isReg() && Op.isImplicit()))
20512       MIB.addOperand(Op);
20513   }
20514   if (MI->hasOneMemOperand())
20515     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20516
20517   BuildMI(*BB, MI, dl,
20518     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20519     .addReg(X86::XMM0);
20520
20521   MI->eraseFromParent();
20522   return BB;
20523 }
20524
20525 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20526 // defs in an instruction pattern
20527 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20528                                        const TargetInstrInfo *TII) {
20529   unsigned Opc;
20530   switch (MI->getOpcode()) {
20531   default: llvm_unreachable("illegal opcode!");
20532   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20533   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20534   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20535   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20536   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20537   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20538   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20539   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20540   }
20541
20542   DebugLoc dl = MI->getDebugLoc();
20543   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20544
20545   unsigned NumArgs = MI->getNumOperands(); // remove the results
20546   for (unsigned i = 1; i < NumArgs; ++i) {
20547     MachineOperand &Op = MI->getOperand(i);
20548     if (!(Op.isReg() && Op.isImplicit()))
20549       MIB.addOperand(Op);
20550   }
20551   if (MI->hasOneMemOperand())
20552     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20553
20554   BuildMI(*BB, MI, dl,
20555     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20556     .addReg(X86::ECX);
20557
20558   MI->eraseFromParent();
20559   return BB;
20560 }
20561
20562 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20563                                       const X86Subtarget *Subtarget) {
20564   DebugLoc dl = MI->getDebugLoc();
20565   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20566   // Address into RAX/EAX, other two args into ECX, EDX.
20567   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20568   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20569   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20570   for (int i = 0; i < X86::AddrNumOperands; ++i)
20571     MIB.addOperand(MI->getOperand(i));
20572
20573   unsigned ValOps = X86::AddrNumOperands;
20574   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20575     .addReg(MI->getOperand(ValOps).getReg());
20576   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20577     .addReg(MI->getOperand(ValOps+1).getReg());
20578
20579   // The instruction doesn't actually take any operands though.
20580   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20581
20582   MI->eraseFromParent(); // The pseudo is gone now.
20583   return BB;
20584 }
20585
20586 MachineBasicBlock *
20587 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20588                                                  MachineBasicBlock *MBB) const {
20589   // Emit va_arg instruction on X86-64.
20590
20591   // Operands to this pseudo-instruction:
20592   // 0  ) Output        : destination address (reg)
20593   // 1-5) Input         : va_list address (addr, i64mem)
20594   // 6  ) ArgSize       : Size (in bytes) of vararg type
20595   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20596   // 8  ) Align         : Alignment of type
20597   // 9  ) EFLAGS (implicit-def)
20598
20599   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20600   static_assert(X86::AddrNumOperands == 5,
20601                 "VAARG_64 assumes 5 address operands");
20602
20603   unsigned DestReg = MI->getOperand(0).getReg();
20604   MachineOperand &Base = MI->getOperand(1);
20605   MachineOperand &Scale = MI->getOperand(2);
20606   MachineOperand &Index = MI->getOperand(3);
20607   MachineOperand &Disp = MI->getOperand(4);
20608   MachineOperand &Segment = MI->getOperand(5);
20609   unsigned ArgSize = MI->getOperand(6).getImm();
20610   unsigned ArgMode = MI->getOperand(7).getImm();
20611   unsigned Align = MI->getOperand(8).getImm();
20612
20613   // Memory Reference
20614   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20615   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20616   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20617
20618   // Machine Information
20619   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20620   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20621   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20622   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20623   DebugLoc DL = MI->getDebugLoc();
20624
20625   // struct va_list {
20626   //   i32   gp_offset
20627   //   i32   fp_offset
20628   //   i64   overflow_area (address)
20629   //   i64   reg_save_area (address)
20630   // }
20631   // sizeof(va_list) = 24
20632   // alignment(va_list) = 8
20633
20634   unsigned TotalNumIntRegs = 6;
20635   unsigned TotalNumXMMRegs = 8;
20636   bool UseGPOffset = (ArgMode == 1);
20637   bool UseFPOffset = (ArgMode == 2);
20638   unsigned MaxOffset = TotalNumIntRegs * 8 +
20639                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20640
20641   /* Align ArgSize to a multiple of 8 */
20642   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20643   bool NeedsAlign = (Align > 8);
20644
20645   MachineBasicBlock *thisMBB = MBB;
20646   MachineBasicBlock *overflowMBB;
20647   MachineBasicBlock *offsetMBB;
20648   MachineBasicBlock *endMBB;
20649
20650   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20651   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20652   unsigned OffsetReg = 0;
20653
20654   if (!UseGPOffset && !UseFPOffset) {
20655     // If we only pull from the overflow region, we don't create a branch.
20656     // We don't need to alter control flow.
20657     OffsetDestReg = 0; // unused
20658     OverflowDestReg = DestReg;
20659
20660     offsetMBB = nullptr;
20661     overflowMBB = thisMBB;
20662     endMBB = thisMBB;
20663   } else {
20664     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20665     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20666     // If not, pull from overflow_area. (branch to overflowMBB)
20667     //
20668     //       thisMBB
20669     //         |     .
20670     //         |        .
20671     //     offsetMBB   overflowMBB
20672     //         |        .
20673     //         |     .
20674     //        endMBB
20675
20676     // Registers for the PHI in endMBB
20677     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20678     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20679
20680     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20681     MachineFunction *MF = MBB->getParent();
20682     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20683     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20684     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20685
20686     MachineFunction::iterator MBBIter = ++MBB->getIterator();
20687
20688     // Insert the new basic blocks
20689     MF->insert(MBBIter, offsetMBB);
20690     MF->insert(MBBIter, overflowMBB);
20691     MF->insert(MBBIter, endMBB);
20692
20693     // Transfer the remainder of MBB and its successor edges to endMBB.
20694     endMBB->splice(endMBB->begin(), thisMBB,
20695                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20696     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20697
20698     // Make offsetMBB and overflowMBB successors of thisMBB
20699     thisMBB->addSuccessor(offsetMBB);
20700     thisMBB->addSuccessor(overflowMBB);
20701
20702     // endMBB is a successor of both offsetMBB and overflowMBB
20703     offsetMBB->addSuccessor(endMBB);
20704     overflowMBB->addSuccessor(endMBB);
20705
20706     // Load the offset value into a register
20707     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20708     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20709       .addOperand(Base)
20710       .addOperand(Scale)
20711       .addOperand(Index)
20712       .addDisp(Disp, UseFPOffset ? 4 : 0)
20713       .addOperand(Segment)
20714       .setMemRefs(MMOBegin, MMOEnd);
20715
20716     // Check if there is enough room left to pull this argument.
20717     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20718       .addReg(OffsetReg)
20719       .addImm(MaxOffset + 8 - ArgSizeA8);
20720
20721     // Branch to "overflowMBB" if offset >= max
20722     // Fall through to "offsetMBB" otherwise
20723     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20724       .addMBB(overflowMBB);
20725   }
20726
20727   // In offsetMBB, emit code to use the reg_save_area.
20728   if (offsetMBB) {
20729     assert(OffsetReg != 0);
20730
20731     // Read the reg_save_area address.
20732     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20733     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20734       .addOperand(Base)
20735       .addOperand(Scale)
20736       .addOperand(Index)
20737       .addDisp(Disp, 16)
20738       .addOperand(Segment)
20739       .setMemRefs(MMOBegin, MMOEnd);
20740
20741     // Zero-extend the offset
20742     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20743       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20744         .addImm(0)
20745         .addReg(OffsetReg)
20746         .addImm(X86::sub_32bit);
20747
20748     // Add the offset to the reg_save_area to get the final address.
20749     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20750       .addReg(OffsetReg64)
20751       .addReg(RegSaveReg);
20752
20753     // Compute the offset for the next argument
20754     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20755     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20756       .addReg(OffsetReg)
20757       .addImm(UseFPOffset ? 16 : 8);
20758
20759     // Store it back into the va_list.
20760     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20761       .addOperand(Base)
20762       .addOperand(Scale)
20763       .addOperand(Index)
20764       .addDisp(Disp, UseFPOffset ? 4 : 0)
20765       .addOperand(Segment)
20766       .addReg(NextOffsetReg)
20767       .setMemRefs(MMOBegin, MMOEnd);
20768
20769     // Jump to endMBB
20770     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20771       .addMBB(endMBB);
20772   }
20773
20774   //
20775   // Emit code to use overflow area
20776   //
20777
20778   // Load the overflow_area address into a register.
20779   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20780   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20781     .addOperand(Base)
20782     .addOperand(Scale)
20783     .addOperand(Index)
20784     .addDisp(Disp, 8)
20785     .addOperand(Segment)
20786     .setMemRefs(MMOBegin, MMOEnd);
20787
20788   // If we need to align it, do so. Otherwise, just copy the address
20789   // to OverflowDestReg.
20790   if (NeedsAlign) {
20791     // Align the overflow address
20792     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20793     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20794
20795     // aligned_addr = (addr + (align-1)) & ~(align-1)
20796     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20797       .addReg(OverflowAddrReg)
20798       .addImm(Align-1);
20799
20800     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20801       .addReg(TmpReg)
20802       .addImm(~(uint64_t)(Align-1));
20803   } else {
20804     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20805       .addReg(OverflowAddrReg);
20806   }
20807
20808   // Compute the next overflow address after this argument.
20809   // (the overflow address should be kept 8-byte aligned)
20810   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20811   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20812     .addReg(OverflowDestReg)
20813     .addImm(ArgSizeA8);
20814
20815   // Store the new overflow address.
20816   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20817     .addOperand(Base)
20818     .addOperand(Scale)
20819     .addOperand(Index)
20820     .addDisp(Disp, 8)
20821     .addOperand(Segment)
20822     .addReg(NextAddrReg)
20823     .setMemRefs(MMOBegin, MMOEnd);
20824
20825   // If we branched, emit the PHI to the front of endMBB.
20826   if (offsetMBB) {
20827     BuildMI(*endMBB, endMBB->begin(), DL,
20828             TII->get(X86::PHI), DestReg)
20829       .addReg(OffsetDestReg).addMBB(offsetMBB)
20830       .addReg(OverflowDestReg).addMBB(overflowMBB);
20831   }
20832
20833   // Erase the pseudo instruction
20834   MI->eraseFromParent();
20835
20836   return endMBB;
20837 }
20838
20839 MachineBasicBlock *
20840 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20841                                                  MachineInstr *MI,
20842                                                  MachineBasicBlock *MBB) const {
20843   // Emit code to save XMM registers to the stack. The ABI says that the
20844   // number of registers to save is given in %al, so it's theoretically
20845   // possible to do an indirect jump trick to avoid saving all of them,
20846   // however this code takes a simpler approach and just executes all
20847   // of the stores if %al is non-zero. It's less code, and it's probably
20848   // easier on the hardware branch predictor, and stores aren't all that
20849   // expensive anyway.
20850
20851   // Create the new basic blocks. One block contains all the XMM stores,
20852   // and one block is the final destination regardless of whether any
20853   // stores were performed.
20854   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20855   MachineFunction *F = MBB->getParent();
20856   MachineFunction::iterator MBBIter = ++MBB->getIterator();
20857   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20858   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20859   F->insert(MBBIter, XMMSaveMBB);
20860   F->insert(MBBIter, EndMBB);
20861
20862   // Transfer the remainder of MBB and its successor edges to EndMBB.
20863   EndMBB->splice(EndMBB->begin(), MBB,
20864                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20865   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20866
20867   // The original block will now fall through to the XMM save block.
20868   MBB->addSuccessor(XMMSaveMBB);
20869   // The XMMSaveMBB will fall through to the end block.
20870   XMMSaveMBB->addSuccessor(EndMBB);
20871
20872   // Now add the instructions.
20873   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20874   DebugLoc DL = MI->getDebugLoc();
20875
20876   unsigned CountReg = MI->getOperand(0).getReg();
20877   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20878   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20879
20880   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20881     // If %al is 0, branch around the XMM save block.
20882     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20883     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20884     MBB->addSuccessor(EndMBB);
20885   }
20886
20887   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20888   // that was just emitted, but clearly shouldn't be "saved".
20889   assert((MI->getNumOperands() <= 3 ||
20890           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20891           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20892          && "Expected last argument to be EFLAGS");
20893   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20894   // In the XMM save block, save all the XMM argument registers.
20895   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20896     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20897     MachineMemOperand *MMO = F->getMachineMemOperand(
20898         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20899         MachineMemOperand::MOStore,
20900         /*Size=*/16, /*Align=*/16);
20901     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20902       .addFrameIndex(RegSaveFrameIndex)
20903       .addImm(/*Scale=*/1)
20904       .addReg(/*IndexReg=*/0)
20905       .addImm(/*Disp=*/Offset)
20906       .addReg(/*Segment=*/0)
20907       .addReg(MI->getOperand(i).getReg())
20908       .addMemOperand(MMO);
20909   }
20910
20911   MI->eraseFromParent();   // The pseudo instruction is gone now.
20912
20913   return EndMBB;
20914 }
20915
20916 // The EFLAGS operand of SelectItr might be missing a kill marker
20917 // because there were multiple uses of EFLAGS, and ISel didn't know
20918 // which to mark. Figure out whether SelectItr should have had a
20919 // kill marker, and set it if it should. Returns the correct kill
20920 // marker value.
20921 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20922                                      MachineBasicBlock* BB,
20923                                      const TargetRegisterInfo* TRI) {
20924   // Scan forward through BB for a use/def of EFLAGS.
20925   MachineBasicBlock::iterator miI(std::next(SelectItr));
20926   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20927     const MachineInstr& mi = *miI;
20928     if (mi.readsRegister(X86::EFLAGS))
20929       return false;
20930     if (mi.definesRegister(X86::EFLAGS))
20931       break; // Should have kill-flag - update below.
20932   }
20933
20934   // If we hit the end of the block, check whether EFLAGS is live into a
20935   // successor.
20936   if (miI == BB->end()) {
20937     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20938                                           sEnd = BB->succ_end();
20939          sItr != sEnd; ++sItr) {
20940       MachineBasicBlock* succ = *sItr;
20941       if (succ->isLiveIn(X86::EFLAGS))
20942         return false;
20943     }
20944   }
20945
20946   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20947   // out. SelectMI should have a kill flag on EFLAGS.
20948   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20949   return true;
20950 }
20951
20952 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20953 // together with other CMOV pseudo-opcodes into a single basic-block with
20954 // conditional jump around it.
20955 static bool isCMOVPseudo(MachineInstr *MI) {
20956   switch (MI->getOpcode()) {
20957   case X86::CMOV_FR32:
20958   case X86::CMOV_FR64:
20959   case X86::CMOV_GR8:
20960   case X86::CMOV_GR16:
20961   case X86::CMOV_GR32:
20962   case X86::CMOV_RFP32:
20963   case X86::CMOV_RFP64:
20964   case X86::CMOV_RFP80:
20965   case X86::CMOV_V2F64:
20966   case X86::CMOV_V2I64:
20967   case X86::CMOV_V4F32:
20968   case X86::CMOV_V4F64:
20969   case X86::CMOV_V4I64:
20970   case X86::CMOV_V16F32:
20971   case X86::CMOV_V8F32:
20972   case X86::CMOV_V8F64:
20973   case X86::CMOV_V8I64:
20974   case X86::CMOV_V8I1:
20975   case X86::CMOV_V16I1:
20976   case X86::CMOV_V32I1:
20977   case X86::CMOV_V64I1:
20978     return true;
20979
20980   default:
20981     return false;
20982   }
20983 }
20984
20985 MachineBasicBlock *
20986 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20987                                      MachineBasicBlock *BB) const {
20988   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20989   DebugLoc DL = MI->getDebugLoc();
20990
20991   // To "insert" a SELECT_CC instruction, we actually have to insert the
20992   // diamond control-flow pattern.  The incoming instruction knows the
20993   // destination vreg to set, the condition code register to branch on, the
20994   // true/false values to select between, and a branch opcode to use.
20995   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20996   MachineFunction::iterator It = ++BB->getIterator();
20997
20998   //  thisMBB:
20999   //  ...
21000   //   TrueVal = ...
21001   //   cmpTY ccX, r1, r2
21002   //   bCC copy1MBB
21003   //   fallthrough --> copy0MBB
21004   MachineBasicBlock *thisMBB = BB;
21005   MachineFunction *F = BB->getParent();
21006
21007   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21008   // as described above, by inserting a BB, and then making a PHI at the join
21009   // point to select the true and false operands of the CMOV in the PHI.
21010   //
21011   // The code also handles two different cases of multiple CMOV opcodes
21012   // in a row.
21013   //
21014   // Case 1:
21015   // In this case, there are multiple CMOVs in a row, all which are based on
21016   // the same condition setting (or the exact opposite condition setting).
21017   // In this case we can lower all the CMOVs using a single inserted BB, and
21018   // then make a number of PHIs at the join point to model the CMOVs. The only
21019   // trickiness here, is that in a case like:
21020   //
21021   // t2 = CMOV cond1 t1, f1
21022   // t3 = CMOV cond1 t2, f2
21023   //
21024   // when rewriting this into PHIs, we have to perform some renaming on the
21025   // temps since you cannot have a PHI operand refer to a PHI result earlier
21026   // in the same block.  The "simple" but wrong lowering would be:
21027   //
21028   // t2 = PHI t1(BB1), f1(BB2)
21029   // t3 = PHI t2(BB1), f2(BB2)
21030   //
21031   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21032   // renaming is to note that on the path through BB1, t2 is really just a
21033   // copy of t1, and do that renaming, properly generating:
21034   //
21035   // t2 = PHI t1(BB1), f1(BB2)
21036   // t3 = PHI t1(BB1), f2(BB2)
21037   //
21038   // Case 2, we lower cascaded CMOVs such as
21039   //
21040   //   (CMOV (CMOV F, T, cc1), T, cc2)
21041   //
21042   // to two successives branches.  For that, we look for another CMOV as the
21043   // following instruction.
21044   //
21045   // Without this, we would add a PHI between the two jumps, which ends up
21046   // creating a few copies all around. For instance, for
21047   //
21048   //    (sitofp (zext (fcmp une)))
21049   //
21050   // we would generate:
21051   //
21052   //         ucomiss %xmm1, %xmm0
21053   //         movss  <1.0f>, %xmm0
21054   //         movaps  %xmm0, %xmm1
21055   //         jne     .LBB5_2
21056   //         xorps   %xmm1, %xmm1
21057   // .LBB5_2:
21058   //         jp      .LBB5_4
21059   //         movaps  %xmm1, %xmm0
21060   // .LBB5_4:
21061   //         retq
21062   //
21063   // because this custom-inserter would have generated:
21064   //
21065   //   A
21066   //   | \
21067   //   |  B
21068   //   | /
21069   //   C
21070   //   | \
21071   //   |  D
21072   //   | /
21073   //   E
21074   //
21075   // A: X = ...; Y = ...
21076   // B: empty
21077   // C: Z = PHI [X, A], [Y, B]
21078   // D: empty
21079   // E: PHI [X, C], [Z, D]
21080   //
21081   // If we lower both CMOVs in a single step, we can instead generate:
21082   //
21083   //   A
21084   //   | \
21085   //   |  C
21086   //   | /|
21087   //   |/ |
21088   //   |  |
21089   //   |  D
21090   //   | /
21091   //   E
21092   //
21093   // A: X = ...; Y = ...
21094   // D: empty
21095   // E: PHI [X, A], [X, C], [Y, D]
21096   //
21097   // Which, in our sitofp/fcmp example, gives us something like:
21098   //
21099   //         ucomiss %xmm1, %xmm0
21100   //         movss  <1.0f>, %xmm0
21101   //         jne     .LBB5_4
21102   //         jp      .LBB5_4
21103   //         xorps   %xmm0, %xmm0
21104   // .LBB5_4:
21105   //         retq
21106   //
21107   MachineInstr *CascadedCMOV = nullptr;
21108   MachineInstr *LastCMOV = MI;
21109   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21110   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21111   MachineBasicBlock::iterator NextMIIt =
21112       std::next(MachineBasicBlock::iterator(MI));
21113
21114   // Check for case 1, where there are multiple CMOVs with the same condition
21115   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21116   // number of jumps the most.
21117
21118   if (isCMOVPseudo(MI)) {
21119     // See if we have a string of CMOVS with the same condition.
21120     while (NextMIIt != BB->end() &&
21121            isCMOVPseudo(NextMIIt) &&
21122            (NextMIIt->getOperand(3).getImm() == CC ||
21123             NextMIIt->getOperand(3).getImm() == OppCC)) {
21124       LastCMOV = &*NextMIIt;
21125       ++NextMIIt;
21126     }
21127   }
21128
21129   // This checks for case 2, but only do this if we didn't already find
21130   // case 1, as indicated by LastCMOV == MI.
21131   if (LastCMOV == MI &&
21132       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21133       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21134       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21135     CascadedCMOV = &*NextMIIt;
21136   }
21137
21138   MachineBasicBlock *jcc1MBB = nullptr;
21139
21140   // If we have a cascaded CMOV, we lower it to two successive branches to
21141   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21142   if (CascadedCMOV) {
21143     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21144     F->insert(It, jcc1MBB);
21145     jcc1MBB->addLiveIn(X86::EFLAGS);
21146   }
21147
21148   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21149   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21150   F->insert(It, copy0MBB);
21151   F->insert(It, sinkMBB);
21152
21153   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21154   // live into the sink and copy blocks.
21155   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21156
21157   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21158   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21159       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21160     copy0MBB->addLiveIn(X86::EFLAGS);
21161     sinkMBB->addLiveIn(X86::EFLAGS);
21162   }
21163
21164   // Transfer the remainder of BB and its successor edges to sinkMBB.
21165   sinkMBB->splice(sinkMBB->begin(), BB,
21166                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21167   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21168
21169   // Add the true and fallthrough blocks as its successors.
21170   if (CascadedCMOV) {
21171     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21172     BB->addSuccessor(jcc1MBB);
21173
21174     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21175     // jump to the sinkMBB.
21176     jcc1MBB->addSuccessor(copy0MBB);
21177     jcc1MBB->addSuccessor(sinkMBB);
21178   } else {
21179     BB->addSuccessor(copy0MBB);
21180   }
21181
21182   // The true block target of the first (or only) branch is always sinkMBB.
21183   BB->addSuccessor(sinkMBB);
21184
21185   // Create the conditional branch instruction.
21186   unsigned Opc = X86::GetCondBranchFromCond(CC);
21187   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21188
21189   if (CascadedCMOV) {
21190     unsigned Opc2 = X86::GetCondBranchFromCond(
21191         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21192     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21193   }
21194
21195   //  copy0MBB:
21196   //   %FalseValue = ...
21197   //   # fallthrough to sinkMBB
21198   copy0MBB->addSuccessor(sinkMBB);
21199
21200   //  sinkMBB:
21201   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21202   //  ...
21203   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21204   MachineBasicBlock::iterator MIItEnd =
21205     std::next(MachineBasicBlock::iterator(LastCMOV));
21206   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21207   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21208   MachineInstrBuilder MIB;
21209
21210   // As we are creating the PHIs, we have to be careful if there is more than
21211   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21212   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21213   // That also means that PHI construction must work forward from earlier to
21214   // later, and that the code must maintain a mapping from earlier PHI's
21215   // destination registers, and the registers that went into the PHI.
21216
21217   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21218     unsigned DestReg = MIIt->getOperand(0).getReg();
21219     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21220     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21221
21222     // If this CMOV we are generating is the opposite condition from
21223     // the jump we generated, then we have to swap the operands for the
21224     // PHI that is going to be generated.
21225     if (MIIt->getOperand(3).getImm() == OppCC)
21226         std::swap(Op1Reg, Op2Reg);
21227
21228     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21229       Op1Reg = RegRewriteTable[Op1Reg].first;
21230
21231     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21232       Op2Reg = RegRewriteTable[Op2Reg].second;
21233
21234     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21235                   TII->get(X86::PHI), DestReg)
21236           .addReg(Op1Reg).addMBB(copy0MBB)
21237           .addReg(Op2Reg).addMBB(thisMBB);
21238
21239     // Add this PHI to the rewrite table.
21240     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21241   }
21242
21243   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21244   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21245   if (CascadedCMOV) {
21246     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21247     // Copy the PHI result to the register defined by the second CMOV.
21248     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21249             DL, TII->get(TargetOpcode::COPY),
21250             CascadedCMOV->getOperand(0).getReg())
21251         .addReg(MI->getOperand(0).getReg());
21252     CascadedCMOV->eraseFromParent();
21253   }
21254
21255   // Now remove the CMOV(s).
21256   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21257     (MIIt++)->eraseFromParent();
21258
21259   return sinkMBB;
21260 }
21261
21262 MachineBasicBlock *
21263 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21264                                        MachineBasicBlock *BB) const {
21265   // Combine the following atomic floating-point modification pattern:
21266   //   a.store(reg OP a.load(acquire), release)
21267   // Transform them into:
21268   //   OPss (%gpr), %xmm
21269   //   movss %xmm, (%gpr)
21270   // Or sd equivalent for 64-bit operations.
21271   unsigned MOp, FOp;
21272   switch (MI->getOpcode()) {
21273   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21274   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21275   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21276   }
21277   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21278   DebugLoc DL = MI->getDebugLoc();
21279   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21280   MachineOperand MSrc = MI->getOperand(0);
21281   unsigned VSrc = MI->getOperand(5).getReg();
21282   const MachineOperand &Disp = MI->getOperand(3);
21283   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21284   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21285   if (hasDisp && MSrc.isReg())
21286     MSrc.setIsKill(false);
21287   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21288                                 .addOperand(/*Base=*/MSrc)
21289                                 .addImm(/*Scale=*/1)
21290                                 .addReg(/*Index=*/0)
21291                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21292                                 .addReg(0);
21293   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21294                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21295                           .addReg(VSrc)
21296                           .addOperand(/*Base=*/MSrc)
21297                           .addImm(/*Scale=*/1)
21298                           .addReg(/*Index=*/0)
21299                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21300                           .addReg(/*Segment=*/0);
21301   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21302   MI->eraseFromParent(); // The pseudo instruction is gone now.
21303   return BB;
21304 }
21305
21306 MachineBasicBlock *
21307 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21308                                         MachineBasicBlock *BB) const {
21309   MachineFunction *MF = BB->getParent();
21310   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21311   DebugLoc DL = MI->getDebugLoc();
21312   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21313
21314   assert(MF->shouldSplitStack());
21315
21316   const bool Is64Bit = Subtarget->is64Bit();
21317   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21318
21319   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21320   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21321
21322   // BB:
21323   //  ... [Till the alloca]
21324   // If stacklet is not large enough, jump to mallocMBB
21325   //
21326   // bumpMBB:
21327   //  Allocate by subtracting from RSP
21328   //  Jump to continueMBB
21329   //
21330   // mallocMBB:
21331   //  Allocate by call to runtime
21332   //
21333   // continueMBB:
21334   //  ...
21335   //  [rest of original BB]
21336   //
21337
21338   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21339   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21340   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21341
21342   MachineRegisterInfo &MRI = MF->getRegInfo();
21343   const TargetRegisterClass *AddrRegClass =
21344       getRegClassFor(getPointerTy(MF->getDataLayout()));
21345
21346   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21347     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21348     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21349     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21350     sizeVReg = MI->getOperand(1).getReg(),
21351     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21352
21353   MachineFunction::iterator MBBIter = ++BB->getIterator();
21354
21355   MF->insert(MBBIter, bumpMBB);
21356   MF->insert(MBBIter, mallocMBB);
21357   MF->insert(MBBIter, continueMBB);
21358
21359   continueMBB->splice(continueMBB->begin(), BB,
21360                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21361   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21362
21363   // Add code to the main basic block to check if the stack limit has been hit,
21364   // and if so, jump to mallocMBB otherwise to bumpMBB.
21365   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21366   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21367     .addReg(tmpSPVReg).addReg(sizeVReg);
21368   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21369     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21370     .addReg(SPLimitVReg);
21371   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21372
21373   // bumpMBB simply decreases the stack pointer, since we know the current
21374   // stacklet has enough space.
21375   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21376     .addReg(SPLimitVReg);
21377   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21378     .addReg(SPLimitVReg);
21379   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21380
21381   // Calls into a routine in libgcc to allocate more space from the heap.
21382   const uint32_t *RegMask =
21383       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21384   if (IsLP64) {
21385     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21386       .addReg(sizeVReg);
21387     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21388       .addExternalSymbol("__morestack_allocate_stack_space")
21389       .addRegMask(RegMask)
21390       .addReg(X86::RDI, RegState::Implicit)
21391       .addReg(X86::RAX, RegState::ImplicitDefine);
21392   } else if (Is64Bit) {
21393     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21394       .addReg(sizeVReg);
21395     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21396       .addExternalSymbol("__morestack_allocate_stack_space")
21397       .addRegMask(RegMask)
21398       .addReg(X86::EDI, RegState::Implicit)
21399       .addReg(X86::EAX, RegState::ImplicitDefine);
21400   } else {
21401     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21402       .addImm(12);
21403     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21404     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21405       .addExternalSymbol("__morestack_allocate_stack_space")
21406       .addRegMask(RegMask)
21407       .addReg(X86::EAX, RegState::ImplicitDefine);
21408   }
21409
21410   if (!Is64Bit)
21411     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21412       .addImm(16);
21413
21414   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21415     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21416   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21417
21418   // Set up the CFG correctly.
21419   BB->addSuccessor(bumpMBB);
21420   BB->addSuccessor(mallocMBB);
21421   mallocMBB->addSuccessor(continueMBB);
21422   bumpMBB->addSuccessor(continueMBB);
21423
21424   // Take care of the PHI nodes.
21425   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21426           MI->getOperand(0).getReg())
21427     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21428     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21429
21430   // Delete the original pseudo instruction.
21431   MI->eraseFromParent();
21432
21433   // And we're done.
21434   return continueMBB;
21435 }
21436
21437 MachineBasicBlock *
21438 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21439                                         MachineBasicBlock *BB) const {
21440   assert(!Subtarget->isTargetMachO());
21441   DebugLoc DL = MI->getDebugLoc();
21442   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21443       *BB->getParent(), *BB, MI, DL, false);
21444   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21445   MI->eraseFromParent(); // The pseudo instruction is gone now.
21446   return ResumeBB;
21447 }
21448
21449 MachineBasicBlock *
21450 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21451                                        MachineBasicBlock *BB) const {
21452   MachineFunction *MF = BB->getParent();
21453   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21454   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21455   DebugLoc DL = MI->getDebugLoc();
21456
21457   assert(!isAsynchronousEHPersonality(
21458              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
21459          "SEH does not use catchret!");
21460
21461   // Only 32-bit EH needs to worry about manually restoring stack pointers.
21462   if (!Subtarget->is32Bit())
21463     return BB;
21464
21465   // C++ EH creates a new target block to hold the restore code, and wires up
21466   // the new block to the return destination with a normal JMP_4.
21467   MachineBasicBlock *RestoreMBB =
21468       MF->CreateMachineBasicBlock(BB->getBasicBlock());
21469   assert(BB->succ_size() == 1);
21470   MF->insert(std::next(BB->getIterator()), RestoreMBB);
21471   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
21472   BB->addSuccessor(RestoreMBB);
21473   MI->getOperand(0).setMBB(RestoreMBB);
21474
21475   auto RestoreMBBI = RestoreMBB->begin();
21476   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
21477   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
21478   return BB;
21479 }
21480
21481 MachineBasicBlock *
21482 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
21483                                        MachineBasicBlock *BB) const {
21484   MachineFunction *MF = BB->getParent();
21485   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21486   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
21487   // Only 32-bit SEH requires special handling for catchpad.
21488   if (IsSEH && Subtarget->is32Bit()) {
21489     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21490     DebugLoc DL = MI->getDebugLoc();
21491     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
21492   }
21493   MI->eraseFromParent();
21494   return BB;
21495 }
21496
21497 MachineBasicBlock *
21498 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21499                                       MachineBasicBlock *BB) const {
21500   // This is pretty easy.  We're taking the value that we received from
21501   // our load from the relocation, sticking it in either RDI (x86-64)
21502   // or EAX and doing an indirect call.  The return value will then
21503   // be in the normal return register.
21504   MachineFunction *F = BB->getParent();
21505   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21506   DebugLoc DL = MI->getDebugLoc();
21507
21508   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21509   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21510
21511   // Get a register mask for the lowered call.
21512   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21513   // proper register mask.
21514   const uint32_t *RegMask =
21515       Subtarget->is64Bit() ?
21516       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
21517       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21518   if (Subtarget->is64Bit()) {
21519     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21520                                       TII->get(X86::MOV64rm), X86::RDI)
21521     .addReg(X86::RIP)
21522     .addImm(0).addReg(0)
21523     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21524                       MI->getOperand(3).getTargetFlags())
21525     .addReg(0);
21526     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21527     addDirectMem(MIB, X86::RDI);
21528     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21529   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21530     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21531                                       TII->get(X86::MOV32rm), X86::EAX)
21532     .addReg(0)
21533     .addImm(0).addReg(0)
21534     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21535                       MI->getOperand(3).getTargetFlags())
21536     .addReg(0);
21537     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21538     addDirectMem(MIB, X86::EAX);
21539     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21540   } else {
21541     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21542                                       TII->get(X86::MOV32rm), X86::EAX)
21543     .addReg(TII->getGlobalBaseReg(F))
21544     .addImm(0).addReg(0)
21545     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21546                       MI->getOperand(3).getTargetFlags())
21547     .addReg(0);
21548     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21549     addDirectMem(MIB, X86::EAX);
21550     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21551   }
21552
21553   MI->eraseFromParent(); // The pseudo instruction is gone now.
21554   return BB;
21555 }
21556
21557 MachineBasicBlock *
21558 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21559                                     MachineBasicBlock *MBB) const {
21560   DebugLoc DL = MI->getDebugLoc();
21561   MachineFunction *MF = MBB->getParent();
21562   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21563   MachineRegisterInfo &MRI = MF->getRegInfo();
21564
21565   const BasicBlock *BB = MBB->getBasicBlock();
21566   MachineFunction::iterator I = ++MBB->getIterator();
21567
21568   // Memory Reference
21569   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21570   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21571
21572   unsigned DstReg;
21573   unsigned MemOpndSlot = 0;
21574
21575   unsigned CurOp = 0;
21576
21577   DstReg = MI->getOperand(CurOp++).getReg();
21578   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21579   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21580   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21581   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21582
21583   MemOpndSlot = CurOp;
21584
21585   MVT PVT = getPointerTy(MF->getDataLayout());
21586   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21587          "Invalid Pointer Size!");
21588
21589   // For v = setjmp(buf), we generate
21590   //
21591   // thisMBB:
21592   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21593   //  SjLjSetup restoreMBB
21594   //
21595   // mainMBB:
21596   //  v_main = 0
21597   //
21598   // sinkMBB:
21599   //  v = phi(main, restore)
21600   //
21601   // restoreMBB:
21602   //  if base pointer being used, load it from frame
21603   //  v_restore = 1
21604
21605   MachineBasicBlock *thisMBB = MBB;
21606   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21607   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21608   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21609   MF->insert(I, mainMBB);
21610   MF->insert(I, sinkMBB);
21611   MF->push_back(restoreMBB);
21612   restoreMBB->setHasAddressTaken();
21613
21614   MachineInstrBuilder MIB;
21615
21616   // Transfer the remainder of BB and its successor edges to sinkMBB.
21617   sinkMBB->splice(sinkMBB->begin(), MBB,
21618                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21619   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21620
21621   // thisMBB:
21622   unsigned PtrStoreOpc = 0;
21623   unsigned LabelReg = 0;
21624   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21625   Reloc::Model RM = MF->getTarget().getRelocationModel();
21626   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21627                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21628
21629   // Prepare IP either in reg or imm.
21630   if (!UseImmLabel) {
21631     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21632     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21633     LabelReg = MRI.createVirtualRegister(PtrRC);
21634     if (Subtarget->is64Bit()) {
21635       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21636               .addReg(X86::RIP)
21637               .addImm(0)
21638               .addReg(0)
21639               .addMBB(restoreMBB)
21640               .addReg(0);
21641     } else {
21642       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21643       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21644               .addReg(XII->getGlobalBaseReg(MF))
21645               .addImm(0)
21646               .addReg(0)
21647               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21648               .addReg(0);
21649     }
21650   } else
21651     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21652   // Store IP
21653   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21654   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21655     if (i == X86::AddrDisp)
21656       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21657     else
21658       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21659   }
21660   if (!UseImmLabel)
21661     MIB.addReg(LabelReg);
21662   else
21663     MIB.addMBB(restoreMBB);
21664   MIB.setMemRefs(MMOBegin, MMOEnd);
21665   // Setup
21666   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21667           .addMBB(restoreMBB);
21668
21669   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21670   MIB.addRegMask(RegInfo->getNoPreservedMask());
21671   thisMBB->addSuccessor(mainMBB);
21672   thisMBB->addSuccessor(restoreMBB);
21673
21674   // mainMBB:
21675   //  EAX = 0
21676   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21677   mainMBB->addSuccessor(sinkMBB);
21678
21679   // sinkMBB:
21680   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21681           TII->get(X86::PHI), DstReg)
21682     .addReg(mainDstReg).addMBB(mainMBB)
21683     .addReg(restoreDstReg).addMBB(restoreMBB);
21684
21685   // restoreMBB:
21686   if (RegInfo->hasBasePointer(*MF)) {
21687     const bool Uses64BitFramePtr =
21688         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21689     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21690     X86FI->setRestoreBasePointer(MF);
21691     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21692     unsigned BasePtr = RegInfo->getBaseRegister();
21693     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21694     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21695                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21696       .setMIFlag(MachineInstr::FrameSetup);
21697   }
21698   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21699   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21700   restoreMBB->addSuccessor(sinkMBB);
21701
21702   MI->eraseFromParent();
21703   return sinkMBB;
21704 }
21705
21706 MachineBasicBlock *
21707 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21708                                      MachineBasicBlock *MBB) const {
21709   DebugLoc DL = MI->getDebugLoc();
21710   MachineFunction *MF = MBB->getParent();
21711   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21712   MachineRegisterInfo &MRI = MF->getRegInfo();
21713
21714   // Memory Reference
21715   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21716   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21717
21718   MVT PVT = getPointerTy(MF->getDataLayout());
21719   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21720          "Invalid Pointer Size!");
21721
21722   const TargetRegisterClass *RC =
21723     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21724   unsigned Tmp = MRI.createVirtualRegister(RC);
21725   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21726   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21727   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21728   unsigned SP = RegInfo->getStackRegister();
21729
21730   MachineInstrBuilder MIB;
21731
21732   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21733   const int64_t SPOffset = 2 * PVT.getStoreSize();
21734
21735   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21736   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21737
21738   // Reload FP
21739   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21740   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21741     MIB.addOperand(MI->getOperand(i));
21742   MIB.setMemRefs(MMOBegin, MMOEnd);
21743   // Reload IP
21744   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21745   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21746     if (i == X86::AddrDisp)
21747       MIB.addDisp(MI->getOperand(i), LabelOffset);
21748     else
21749       MIB.addOperand(MI->getOperand(i));
21750   }
21751   MIB.setMemRefs(MMOBegin, MMOEnd);
21752   // Reload SP
21753   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21754   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21755     if (i == X86::AddrDisp)
21756       MIB.addDisp(MI->getOperand(i), SPOffset);
21757     else
21758       MIB.addOperand(MI->getOperand(i));
21759   }
21760   MIB.setMemRefs(MMOBegin, MMOEnd);
21761   // Jump
21762   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21763
21764   MI->eraseFromParent();
21765   return MBB;
21766 }
21767
21768 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21769 // accumulator loops. Writing back to the accumulator allows the coalescer
21770 // to remove extra copies in the loop.
21771 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21772 MachineBasicBlock *
21773 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21774                                  MachineBasicBlock *MBB) const {
21775   MachineOperand &AddendOp = MI->getOperand(3);
21776
21777   // Bail out early if the addend isn't a register - we can't switch these.
21778   if (!AddendOp.isReg())
21779     return MBB;
21780
21781   MachineFunction &MF = *MBB->getParent();
21782   MachineRegisterInfo &MRI = MF.getRegInfo();
21783
21784   // Check whether the addend is defined by a PHI:
21785   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21786   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21787   if (!AddendDef.isPHI())
21788     return MBB;
21789
21790   // Look for the following pattern:
21791   // loop:
21792   //   %addend = phi [%entry, 0], [%loop, %result]
21793   //   ...
21794   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21795
21796   // Replace with:
21797   //   loop:
21798   //   %addend = phi [%entry, 0], [%loop, %result]
21799   //   ...
21800   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21801
21802   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21803     assert(AddendDef.getOperand(i).isReg());
21804     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21805     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21806     if (&PHISrcInst == MI) {
21807       // Found a matching instruction.
21808       unsigned NewFMAOpc = 0;
21809       switch (MI->getOpcode()) {
21810         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21811         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21812         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21813         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21814         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21815         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21816         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21817         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21818         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21819         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21820         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21821         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21822         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21823         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21824         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21825         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21826         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21827         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21828         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21829         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21830
21831         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21832         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21833         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21834         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21835         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21836         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21837         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21838         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21839         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21840         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21841         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21842         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21843         default: llvm_unreachable("Unrecognized FMA variant.");
21844       }
21845
21846       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21847       MachineInstrBuilder MIB =
21848         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21849         .addOperand(MI->getOperand(0))
21850         .addOperand(MI->getOperand(3))
21851         .addOperand(MI->getOperand(2))
21852         .addOperand(MI->getOperand(1));
21853       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21854       MI->eraseFromParent();
21855     }
21856   }
21857
21858   return MBB;
21859 }
21860
21861 MachineBasicBlock *
21862 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21863                                                MachineBasicBlock *BB) const {
21864   switch (MI->getOpcode()) {
21865   default: llvm_unreachable("Unexpected instr type to insert");
21866   case X86::TAILJMPd64:
21867   case X86::TAILJMPr64:
21868   case X86::TAILJMPm64:
21869   case X86::TAILJMPd64_REX:
21870   case X86::TAILJMPr64_REX:
21871   case X86::TAILJMPm64_REX:
21872     llvm_unreachable("TAILJMP64 would not be touched here.");
21873   case X86::TCRETURNdi64:
21874   case X86::TCRETURNri64:
21875   case X86::TCRETURNmi64:
21876     return BB;
21877   case X86::WIN_ALLOCA:
21878     return EmitLoweredWinAlloca(MI, BB);
21879   case X86::CATCHRET:
21880     return EmitLoweredCatchRet(MI, BB);
21881   case X86::CATCHPAD:
21882     return EmitLoweredCatchPad(MI, BB);
21883   case X86::SEG_ALLOCA_32:
21884   case X86::SEG_ALLOCA_64:
21885     return EmitLoweredSegAlloca(MI, BB);
21886   case X86::TLSCall_32:
21887   case X86::TLSCall_64:
21888     return EmitLoweredTLSCall(MI, BB);
21889   case X86::CMOV_FR32:
21890   case X86::CMOV_FR64:
21891   case X86::CMOV_GR8:
21892   case X86::CMOV_GR16:
21893   case X86::CMOV_GR32:
21894   case X86::CMOV_RFP32:
21895   case X86::CMOV_RFP64:
21896   case X86::CMOV_RFP80:
21897   case X86::CMOV_V2F64:
21898   case X86::CMOV_V2I64:
21899   case X86::CMOV_V4F32:
21900   case X86::CMOV_V4F64:
21901   case X86::CMOV_V4I64:
21902   case X86::CMOV_V16F32:
21903   case X86::CMOV_V8F32:
21904   case X86::CMOV_V8F64:
21905   case X86::CMOV_V8I64:
21906   case X86::CMOV_V8I1:
21907   case X86::CMOV_V16I1:
21908   case X86::CMOV_V32I1:
21909   case X86::CMOV_V64I1:
21910     return EmitLoweredSelect(MI, BB);
21911
21912   case X86::RELEASE_FADD32mr:
21913   case X86::RELEASE_FADD64mr:
21914     return EmitLoweredAtomicFP(MI, BB);
21915
21916   case X86::FP32_TO_INT16_IN_MEM:
21917   case X86::FP32_TO_INT32_IN_MEM:
21918   case X86::FP32_TO_INT64_IN_MEM:
21919   case X86::FP64_TO_INT16_IN_MEM:
21920   case X86::FP64_TO_INT32_IN_MEM:
21921   case X86::FP64_TO_INT64_IN_MEM:
21922   case X86::FP80_TO_INT16_IN_MEM:
21923   case X86::FP80_TO_INT32_IN_MEM:
21924   case X86::FP80_TO_INT64_IN_MEM: {
21925     MachineFunction *F = BB->getParent();
21926     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21927     DebugLoc DL = MI->getDebugLoc();
21928
21929     // Change the floating point control register to use "round towards zero"
21930     // mode when truncating to an integer value.
21931     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21932     addFrameReference(BuildMI(*BB, MI, DL,
21933                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21934
21935     // Load the old value of the high byte of the control word...
21936     unsigned OldCW =
21937       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21938     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21939                       CWFrameIdx);
21940
21941     // Set the high part to be round to zero...
21942     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21943       .addImm(0xC7F);
21944
21945     // Reload the modified control word now...
21946     addFrameReference(BuildMI(*BB, MI, DL,
21947                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21948
21949     // Restore the memory image of control word to original value
21950     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21951       .addReg(OldCW);
21952
21953     // Get the X86 opcode to use.
21954     unsigned Opc;
21955     switch (MI->getOpcode()) {
21956     default: llvm_unreachable("illegal opcode!");
21957     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21958     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21959     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21960     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21961     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21962     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21963     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21964     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21965     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21966     }
21967
21968     X86AddressMode AM;
21969     MachineOperand &Op = MI->getOperand(0);
21970     if (Op.isReg()) {
21971       AM.BaseType = X86AddressMode::RegBase;
21972       AM.Base.Reg = Op.getReg();
21973     } else {
21974       AM.BaseType = X86AddressMode::FrameIndexBase;
21975       AM.Base.FrameIndex = Op.getIndex();
21976     }
21977     Op = MI->getOperand(1);
21978     if (Op.isImm())
21979       AM.Scale = Op.getImm();
21980     Op = MI->getOperand(2);
21981     if (Op.isImm())
21982       AM.IndexReg = Op.getImm();
21983     Op = MI->getOperand(3);
21984     if (Op.isGlobal()) {
21985       AM.GV = Op.getGlobal();
21986     } else {
21987       AM.Disp = Op.getImm();
21988     }
21989     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21990                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21991
21992     // Reload the original control word now.
21993     addFrameReference(BuildMI(*BB, MI, DL,
21994                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21995
21996     MI->eraseFromParent();   // The pseudo instruction is gone now.
21997     return BB;
21998   }
21999     // String/text processing lowering.
22000   case X86::PCMPISTRM128REG:
22001   case X86::VPCMPISTRM128REG:
22002   case X86::PCMPISTRM128MEM:
22003   case X86::VPCMPISTRM128MEM:
22004   case X86::PCMPESTRM128REG:
22005   case X86::VPCMPESTRM128REG:
22006   case X86::PCMPESTRM128MEM:
22007   case X86::VPCMPESTRM128MEM:
22008     assert(Subtarget->hasSSE42() &&
22009            "Target must have SSE4.2 or AVX features enabled");
22010     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22011
22012   // String/text processing lowering.
22013   case X86::PCMPISTRIREG:
22014   case X86::VPCMPISTRIREG:
22015   case X86::PCMPISTRIMEM:
22016   case X86::VPCMPISTRIMEM:
22017   case X86::PCMPESTRIREG:
22018   case X86::VPCMPESTRIREG:
22019   case X86::PCMPESTRIMEM:
22020   case X86::VPCMPESTRIMEM:
22021     assert(Subtarget->hasSSE42() &&
22022            "Target must have SSE4.2 or AVX features enabled");
22023     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22024
22025   // Thread synchronization.
22026   case X86::MONITOR:
22027     return EmitMonitor(MI, BB, Subtarget);
22028
22029   // xbegin
22030   case X86::XBEGIN:
22031     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22032
22033   case X86::VASTART_SAVE_XMM_REGS:
22034     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22035
22036   case X86::VAARG_64:
22037     return EmitVAARG64WithCustomInserter(MI, BB);
22038
22039   case X86::EH_SjLj_SetJmp32:
22040   case X86::EH_SjLj_SetJmp64:
22041     return emitEHSjLjSetJmp(MI, BB);
22042
22043   case X86::EH_SjLj_LongJmp32:
22044   case X86::EH_SjLj_LongJmp64:
22045     return emitEHSjLjLongJmp(MI, BB);
22046
22047   case TargetOpcode::STATEPOINT:
22048     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22049     // this point in the process.  We diverge later.
22050     return emitPatchPoint(MI, BB);
22051
22052   case TargetOpcode::STACKMAP:
22053   case TargetOpcode::PATCHPOINT:
22054     return emitPatchPoint(MI, BB);
22055
22056   case X86::VFMADDPDr213r:
22057   case X86::VFMADDPSr213r:
22058   case X86::VFMADDSDr213r:
22059   case X86::VFMADDSSr213r:
22060   case X86::VFMSUBPDr213r:
22061   case X86::VFMSUBPSr213r:
22062   case X86::VFMSUBSDr213r:
22063   case X86::VFMSUBSSr213r:
22064   case X86::VFNMADDPDr213r:
22065   case X86::VFNMADDPSr213r:
22066   case X86::VFNMADDSDr213r:
22067   case X86::VFNMADDSSr213r:
22068   case X86::VFNMSUBPDr213r:
22069   case X86::VFNMSUBPSr213r:
22070   case X86::VFNMSUBSDr213r:
22071   case X86::VFNMSUBSSr213r:
22072   case X86::VFMADDSUBPDr213r:
22073   case X86::VFMADDSUBPSr213r:
22074   case X86::VFMSUBADDPDr213r:
22075   case X86::VFMSUBADDPSr213r:
22076   case X86::VFMADDPDr213rY:
22077   case X86::VFMADDPSr213rY:
22078   case X86::VFMSUBPDr213rY:
22079   case X86::VFMSUBPSr213rY:
22080   case X86::VFNMADDPDr213rY:
22081   case X86::VFNMADDPSr213rY:
22082   case X86::VFNMSUBPDr213rY:
22083   case X86::VFNMSUBPSr213rY:
22084   case X86::VFMADDSUBPDr213rY:
22085   case X86::VFMADDSUBPSr213rY:
22086   case X86::VFMSUBADDPDr213rY:
22087   case X86::VFMSUBADDPSr213rY:
22088     return emitFMA3Instr(MI, BB);
22089   }
22090 }
22091
22092 //===----------------------------------------------------------------------===//
22093 //                           X86 Optimization Hooks
22094 //===----------------------------------------------------------------------===//
22095
22096 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22097                                                       APInt &KnownZero,
22098                                                       APInt &KnownOne,
22099                                                       const SelectionDAG &DAG,
22100                                                       unsigned Depth) const {
22101   unsigned BitWidth = KnownZero.getBitWidth();
22102   unsigned Opc = Op.getOpcode();
22103   assert((Opc >= ISD::BUILTIN_OP_END ||
22104           Opc == ISD::INTRINSIC_WO_CHAIN ||
22105           Opc == ISD::INTRINSIC_W_CHAIN ||
22106           Opc == ISD::INTRINSIC_VOID) &&
22107          "Should use MaskedValueIsZero if you don't know whether Op"
22108          " is a target node!");
22109
22110   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22111   switch (Opc) {
22112   default: break;
22113   case X86ISD::ADD:
22114   case X86ISD::SUB:
22115   case X86ISD::ADC:
22116   case X86ISD::SBB:
22117   case X86ISD::SMUL:
22118   case X86ISD::UMUL:
22119   case X86ISD::INC:
22120   case X86ISD::DEC:
22121   case X86ISD::OR:
22122   case X86ISD::XOR:
22123   case X86ISD::AND:
22124     // These nodes' second result is a boolean.
22125     if (Op.getResNo() == 0)
22126       break;
22127     // Fallthrough
22128   case X86ISD::SETCC:
22129     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22130     break;
22131   case ISD::INTRINSIC_WO_CHAIN: {
22132     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22133     unsigned NumLoBits = 0;
22134     switch (IntId) {
22135     default: break;
22136     case Intrinsic::x86_sse_movmsk_ps:
22137     case Intrinsic::x86_avx_movmsk_ps_256:
22138     case Intrinsic::x86_sse2_movmsk_pd:
22139     case Intrinsic::x86_avx_movmsk_pd_256:
22140     case Intrinsic::x86_mmx_pmovmskb:
22141     case Intrinsic::x86_sse2_pmovmskb_128:
22142     case Intrinsic::x86_avx2_pmovmskb: {
22143       // High bits of movmskp{s|d}, pmovmskb are known zero.
22144       switch (IntId) {
22145         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22146         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22147         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22148         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22149         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22150         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22151         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22152         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22153       }
22154       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22155       break;
22156     }
22157     }
22158     break;
22159   }
22160   }
22161 }
22162
22163 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22164   SDValue Op,
22165   const SelectionDAG &,
22166   unsigned Depth) const {
22167   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22168   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22169     return Op.getValueType().getScalarSizeInBits();
22170
22171   // Fallback case.
22172   return 1;
22173 }
22174
22175 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22176 /// node is a GlobalAddress + offset.
22177 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22178                                        const GlobalValue* &GA,
22179                                        int64_t &Offset) const {
22180   if (N->getOpcode() == X86ISD::Wrapper) {
22181     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22182       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22183       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22184       return true;
22185     }
22186   }
22187   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22188 }
22189
22190 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22191 /// same as extracting the high 128-bit part of 256-bit vector and then
22192 /// inserting the result into the low part of a new 256-bit vector
22193 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22194   EVT VT = SVOp->getValueType(0);
22195   unsigned NumElems = VT.getVectorNumElements();
22196
22197   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22198   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22199     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22200         SVOp->getMaskElt(j) >= 0)
22201       return false;
22202
22203   return true;
22204 }
22205
22206 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22207 /// same as extracting the low 128-bit part of 256-bit vector and then
22208 /// inserting the result into the high part of a new 256-bit vector
22209 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22210   EVT VT = SVOp->getValueType(0);
22211   unsigned NumElems = VT.getVectorNumElements();
22212
22213   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22214   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22215     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22216         SVOp->getMaskElt(j) >= 0)
22217       return false;
22218
22219   return true;
22220 }
22221
22222 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22223 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22224                                         TargetLowering::DAGCombinerInfo &DCI,
22225                                         const X86Subtarget* Subtarget) {
22226   SDLoc dl(N);
22227   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22228   SDValue V1 = SVOp->getOperand(0);
22229   SDValue V2 = SVOp->getOperand(1);
22230   EVT VT = SVOp->getValueType(0);
22231   unsigned NumElems = VT.getVectorNumElements();
22232
22233   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22234       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22235     //
22236     //                   0,0,0,...
22237     //                      |
22238     //    V      UNDEF    BUILD_VECTOR    UNDEF
22239     //     \      /           \           /
22240     //  CONCAT_VECTOR         CONCAT_VECTOR
22241     //         \                  /
22242     //          \                /
22243     //          RESULT: V + zero extended
22244     //
22245     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22246         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22247         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22248       return SDValue();
22249
22250     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22251       return SDValue();
22252
22253     // To match the shuffle mask, the first half of the mask should
22254     // be exactly the first vector, and all the rest a splat with the
22255     // first element of the second one.
22256     for (unsigned i = 0; i != NumElems/2; ++i)
22257       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22258           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22259         return SDValue();
22260
22261     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22262     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22263       if (Ld->hasNUsesOfValue(1, 0)) {
22264         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22265         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22266         SDValue ResNode =
22267           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22268                                   Ld->getMemoryVT(),
22269                                   Ld->getPointerInfo(),
22270                                   Ld->getAlignment(),
22271                                   false/*isVolatile*/, true/*ReadMem*/,
22272                                   false/*WriteMem*/);
22273
22274         // Make sure the newly-created LOAD is in the same position as Ld in
22275         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22276         // and update uses of Ld's output chain to use the TokenFactor.
22277         if (Ld->hasAnyUseOfValue(1)) {
22278           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22279                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22280           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22281           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22282                                  SDValue(ResNode.getNode(), 1));
22283         }
22284
22285         return DAG.getBitcast(VT, ResNode);
22286       }
22287     }
22288
22289     // Emit a zeroed vector and insert the desired subvector on its
22290     // first half.
22291     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22292     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22293     return DCI.CombineTo(N, InsV);
22294   }
22295
22296   //===--------------------------------------------------------------------===//
22297   // Combine some shuffles into subvector extracts and inserts:
22298   //
22299
22300   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22301   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22302     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22303     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22304     return DCI.CombineTo(N, InsV);
22305   }
22306
22307   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22308   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22309     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22310     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22311     return DCI.CombineTo(N, InsV);
22312   }
22313
22314   return SDValue();
22315 }
22316
22317 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22318 /// possible.
22319 ///
22320 /// This is the leaf of the recursive combinine below. When we have found some
22321 /// chain of single-use x86 shuffle instructions and accumulated the combined
22322 /// shuffle mask represented by them, this will try to pattern match that mask
22323 /// into either a single instruction if there is a special purpose instruction
22324 /// for this operation, or into a PSHUFB instruction which is a fully general
22325 /// instruction but should only be used to replace chains over a certain depth.
22326 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22327                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22328                                    TargetLowering::DAGCombinerInfo &DCI,
22329                                    const X86Subtarget *Subtarget) {
22330   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22331
22332   // Find the operand that enters the chain. Note that multiple uses are OK
22333   // here, we're not going to remove the operand we find.
22334   SDValue Input = Op.getOperand(0);
22335   while (Input.getOpcode() == ISD::BITCAST)
22336     Input = Input.getOperand(0);
22337
22338   MVT VT = Input.getSimpleValueType();
22339   MVT RootVT = Root.getSimpleValueType();
22340   SDLoc DL(Root);
22341
22342   if (Mask.size() == 1) {
22343     int Index = Mask[0];
22344     assert((Index >= 0 || Index == SM_SentinelUndef ||
22345             Index == SM_SentinelZero) &&
22346            "Invalid shuffle index found!");
22347
22348     // We may end up with an accumulated mask of size 1 as a result of
22349     // widening of shuffle operands (see function canWidenShuffleElements).
22350     // If the only shuffle index is equal to SM_SentinelZero then propagate
22351     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22352     // mask, and therefore the entire chain of shuffles can be folded away.
22353     if (Index == SM_SentinelZero)
22354       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22355     else
22356       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22357                     /*AddTo*/ true);
22358     return true;
22359   }
22360
22361   // Use the float domain if the operand type is a floating point type.
22362   bool FloatDomain = VT.isFloatingPoint();
22363
22364   // For floating point shuffles, we don't have free copies in the shuffle
22365   // instructions or the ability to load as part of the instruction, so
22366   // canonicalize their shuffles to UNPCK or MOV variants.
22367   //
22368   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22369   // vectors because it can have a load folded into it that UNPCK cannot. This
22370   // doesn't preclude something switching to the shorter encoding post-RA.
22371   //
22372   // FIXME: Should teach these routines about AVX vector widths.
22373   if (FloatDomain && VT.is128BitVector()) {
22374     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22375       bool Lo = Mask.equals({0, 0});
22376       unsigned Shuffle;
22377       MVT ShuffleVT;
22378       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22379       // is no slower than UNPCKLPD but has the option to fold the input operand
22380       // into even an unaligned memory load.
22381       if (Lo && Subtarget->hasSSE3()) {
22382         Shuffle = X86ISD::MOVDDUP;
22383         ShuffleVT = MVT::v2f64;
22384       } else {
22385         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22386         // than the UNPCK variants.
22387         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22388         ShuffleVT = MVT::v4f32;
22389       }
22390       if (Depth == 1 && Root->getOpcode() == Shuffle)
22391         return false; // Nothing to do!
22392       Op = DAG.getBitcast(ShuffleVT, Input);
22393       DCI.AddToWorklist(Op.getNode());
22394       if (Shuffle == X86ISD::MOVDDUP)
22395         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22396       else
22397         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22398       DCI.AddToWorklist(Op.getNode());
22399       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22400                     /*AddTo*/ true);
22401       return true;
22402     }
22403     if (Subtarget->hasSSE3() &&
22404         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22405       bool Lo = Mask.equals({0, 0, 2, 2});
22406       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22407       MVT ShuffleVT = MVT::v4f32;
22408       if (Depth == 1 && Root->getOpcode() == Shuffle)
22409         return false; // Nothing to do!
22410       Op = DAG.getBitcast(ShuffleVT, Input);
22411       DCI.AddToWorklist(Op.getNode());
22412       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22413       DCI.AddToWorklist(Op.getNode());
22414       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22415                     /*AddTo*/ true);
22416       return true;
22417     }
22418     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22419       bool Lo = Mask.equals({0, 0, 1, 1});
22420       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22421       MVT ShuffleVT = MVT::v4f32;
22422       if (Depth == 1 && Root->getOpcode() == Shuffle)
22423         return false; // Nothing to do!
22424       Op = DAG.getBitcast(ShuffleVT, Input);
22425       DCI.AddToWorklist(Op.getNode());
22426       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22427       DCI.AddToWorklist(Op.getNode());
22428       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22429                     /*AddTo*/ true);
22430       return true;
22431     }
22432   }
22433
22434   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22435   // variants as none of these have single-instruction variants that are
22436   // superior to the UNPCK formulation.
22437   if (!FloatDomain && VT.is128BitVector() &&
22438       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22439        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22440        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22441        Mask.equals(
22442            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22443     bool Lo = Mask[0] == 0;
22444     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22445     if (Depth == 1 && Root->getOpcode() == Shuffle)
22446       return false; // Nothing to do!
22447     MVT ShuffleVT;
22448     switch (Mask.size()) {
22449     case 8:
22450       ShuffleVT = MVT::v8i16;
22451       break;
22452     case 16:
22453       ShuffleVT = MVT::v16i8;
22454       break;
22455     default:
22456       llvm_unreachable("Impossible mask size!");
22457     };
22458     Op = DAG.getBitcast(ShuffleVT, Input);
22459     DCI.AddToWorklist(Op.getNode());
22460     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22461     DCI.AddToWorklist(Op.getNode());
22462     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22463                   /*AddTo*/ true);
22464     return true;
22465   }
22466
22467   // Don't try to re-form single instruction chains under any circumstances now
22468   // that we've done encoding canonicalization for them.
22469   if (Depth < 2)
22470     return false;
22471
22472   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22473   // can replace them with a single PSHUFB instruction profitably. Intel's
22474   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22475   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22476   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22477     SmallVector<SDValue, 16> PSHUFBMask;
22478     int NumBytes = VT.getSizeInBits() / 8;
22479     int Ratio = NumBytes / Mask.size();
22480     for (int i = 0; i < NumBytes; ++i) {
22481       if (Mask[i / Ratio] == SM_SentinelUndef) {
22482         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22483         continue;
22484       }
22485       int M = Mask[i / Ratio] != SM_SentinelZero
22486                   ? Ratio * Mask[i / Ratio] + i % Ratio
22487                   : 255;
22488       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22489     }
22490     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22491     Op = DAG.getBitcast(ByteVT, Input);
22492     DCI.AddToWorklist(Op.getNode());
22493     SDValue PSHUFBMaskOp =
22494         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22495     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22496     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22497     DCI.AddToWorklist(Op.getNode());
22498     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22499                   /*AddTo*/ true);
22500     return true;
22501   }
22502
22503   // Failed to find any combines.
22504   return false;
22505 }
22506
22507 /// \brief Fully generic combining of x86 shuffle instructions.
22508 ///
22509 /// This should be the last combine run over the x86 shuffle instructions. Once
22510 /// they have been fully optimized, this will recursively consider all chains
22511 /// of single-use shuffle instructions, build a generic model of the cumulative
22512 /// shuffle operation, and check for simpler instructions which implement this
22513 /// operation. We use this primarily for two purposes:
22514 ///
22515 /// 1) Collapse generic shuffles to specialized single instructions when
22516 ///    equivalent. In most cases, this is just an encoding size win, but
22517 ///    sometimes we will collapse multiple generic shuffles into a single
22518 ///    special-purpose shuffle.
22519 /// 2) Look for sequences of shuffle instructions with 3 or more total
22520 ///    instructions, and replace them with the slightly more expensive SSSE3
22521 ///    PSHUFB instruction if available. We do this as the last combining step
22522 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22523 ///    a suitable short sequence of other instructions. The PHUFB will either
22524 ///    use a register or have to read from memory and so is slightly (but only
22525 ///    slightly) more expensive than the other shuffle instructions.
22526 ///
22527 /// Because this is inherently a quadratic operation (for each shuffle in
22528 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22529 /// This should never be an issue in practice as the shuffle lowering doesn't
22530 /// produce sequences of more than 8 instructions.
22531 ///
22532 /// FIXME: We will currently miss some cases where the redundant shuffling
22533 /// would simplify under the threshold for PSHUFB formation because of
22534 /// combine-ordering. To fix this, we should do the redundant instruction
22535 /// combining in this recursive walk.
22536 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22537                                           ArrayRef<int> RootMask,
22538                                           int Depth, bool HasPSHUFB,
22539                                           SelectionDAG &DAG,
22540                                           TargetLowering::DAGCombinerInfo &DCI,
22541                                           const X86Subtarget *Subtarget) {
22542   // Bound the depth of our recursive combine because this is ultimately
22543   // quadratic in nature.
22544   if (Depth > 8)
22545     return false;
22546
22547   // Directly rip through bitcasts to find the underlying operand.
22548   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22549     Op = Op.getOperand(0);
22550
22551   MVT VT = Op.getSimpleValueType();
22552   if (!VT.isVector())
22553     return false; // Bail if we hit a non-vector.
22554
22555   assert(Root.getSimpleValueType().isVector() &&
22556          "Shuffles operate on vector types!");
22557   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22558          "Can only combine shuffles of the same vector register size.");
22559
22560   if (!isTargetShuffle(Op.getOpcode()))
22561     return false;
22562   SmallVector<int, 16> OpMask;
22563   bool IsUnary;
22564   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22565   // We only can combine unary shuffles which we can decode the mask for.
22566   if (!HaveMask || !IsUnary)
22567     return false;
22568
22569   assert(VT.getVectorNumElements() == OpMask.size() &&
22570          "Different mask size from vector size!");
22571   assert(((RootMask.size() > OpMask.size() &&
22572            RootMask.size() % OpMask.size() == 0) ||
22573           (OpMask.size() > RootMask.size() &&
22574            OpMask.size() % RootMask.size() == 0) ||
22575           OpMask.size() == RootMask.size()) &&
22576          "The smaller number of elements must divide the larger.");
22577   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22578   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22579   assert(((RootRatio == 1 && OpRatio == 1) ||
22580           (RootRatio == 1) != (OpRatio == 1)) &&
22581          "Must not have a ratio for both incoming and op masks!");
22582
22583   SmallVector<int, 16> Mask;
22584   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22585
22586   // Merge this shuffle operation's mask into our accumulated mask. Note that
22587   // this shuffle's mask will be the first applied to the input, followed by the
22588   // root mask to get us all the way to the root value arrangement. The reason
22589   // for this order is that we are recursing up the operation chain.
22590   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22591     int RootIdx = i / RootRatio;
22592     if (RootMask[RootIdx] < 0) {
22593       // This is a zero or undef lane, we're done.
22594       Mask.push_back(RootMask[RootIdx]);
22595       continue;
22596     }
22597
22598     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22599     int OpIdx = RootMaskedIdx / OpRatio;
22600     if (OpMask[OpIdx] < 0) {
22601       // The incoming lanes are zero or undef, it doesn't matter which ones we
22602       // are using.
22603       Mask.push_back(OpMask[OpIdx]);
22604       continue;
22605     }
22606
22607     // Ok, we have non-zero lanes, map them through.
22608     Mask.push_back(OpMask[OpIdx] * OpRatio +
22609                    RootMaskedIdx % OpRatio);
22610   }
22611
22612   // See if we can recurse into the operand to combine more things.
22613   switch (Op.getOpcode()) {
22614   case X86ISD::PSHUFB:
22615     HasPSHUFB = true;
22616   case X86ISD::PSHUFD:
22617   case X86ISD::PSHUFHW:
22618   case X86ISD::PSHUFLW:
22619     if (Op.getOperand(0).hasOneUse() &&
22620         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22621                                       HasPSHUFB, DAG, DCI, Subtarget))
22622       return true;
22623     break;
22624
22625   case X86ISD::UNPCKL:
22626   case X86ISD::UNPCKH:
22627     assert(Op.getOperand(0) == Op.getOperand(1) &&
22628            "We only combine unary shuffles!");
22629     // We can't check for single use, we have to check that this shuffle is the
22630     // only user.
22631     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22632         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22633                                       HasPSHUFB, DAG, DCI, Subtarget))
22634       return true;
22635     break;
22636   }
22637
22638   // Minor canonicalization of the accumulated shuffle mask to make it easier
22639   // to match below. All this does is detect masks with squential pairs of
22640   // elements, and shrink them to the half-width mask. It does this in a loop
22641   // so it will reduce the size of the mask to the minimal width mask which
22642   // performs an equivalent shuffle.
22643   SmallVector<int, 16> WidenedMask;
22644   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22645     Mask = std::move(WidenedMask);
22646     WidenedMask.clear();
22647   }
22648
22649   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22650                                 Subtarget);
22651 }
22652
22653 /// \brief Get the PSHUF-style mask from PSHUF node.
22654 ///
22655 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22656 /// PSHUF-style masks that can be reused with such instructions.
22657 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22658   MVT VT = N.getSimpleValueType();
22659   SmallVector<int, 4> Mask;
22660   bool IsUnary;
22661   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22662   (void)HaveMask;
22663   assert(HaveMask);
22664
22665   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22666   // matter. Check that the upper masks are repeats and remove them.
22667   if (VT.getSizeInBits() > 128) {
22668     int LaneElts = 128 / VT.getScalarSizeInBits();
22669 #ifndef NDEBUG
22670     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22671       for (int j = 0; j < LaneElts; ++j)
22672         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22673                "Mask doesn't repeat in high 128-bit lanes!");
22674 #endif
22675     Mask.resize(LaneElts);
22676   }
22677
22678   switch (N.getOpcode()) {
22679   case X86ISD::PSHUFD:
22680     return Mask;
22681   case X86ISD::PSHUFLW:
22682     Mask.resize(4);
22683     return Mask;
22684   case X86ISD::PSHUFHW:
22685     Mask.erase(Mask.begin(), Mask.begin() + 4);
22686     for (int &M : Mask)
22687       M -= 4;
22688     return Mask;
22689   default:
22690     llvm_unreachable("No valid shuffle instruction found!");
22691   }
22692 }
22693
22694 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22695 ///
22696 /// We walk up the chain and look for a combinable shuffle, skipping over
22697 /// shuffles that we could hoist this shuffle's transformation past without
22698 /// altering anything.
22699 static SDValue
22700 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22701                              SelectionDAG &DAG,
22702                              TargetLowering::DAGCombinerInfo &DCI) {
22703   assert(N.getOpcode() == X86ISD::PSHUFD &&
22704          "Called with something other than an x86 128-bit half shuffle!");
22705   SDLoc DL(N);
22706
22707   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22708   // of the shuffles in the chain so that we can form a fresh chain to replace
22709   // this one.
22710   SmallVector<SDValue, 8> Chain;
22711   SDValue V = N.getOperand(0);
22712   for (; V.hasOneUse(); V = V.getOperand(0)) {
22713     switch (V.getOpcode()) {
22714     default:
22715       return SDValue(); // Nothing combined!
22716
22717     case ISD::BITCAST:
22718       // Skip bitcasts as we always know the type for the target specific
22719       // instructions.
22720       continue;
22721
22722     case X86ISD::PSHUFD:
22723       // Found another dword shuffle.
22724       break;
22725
22726     case X86ISD::PSHUFLW:
22727       // Check that the low words (being shuffled) are the identity in the
22728       // dword shuffle, and the high words are self-contained.
22729       if (Mask[0] != 0 || Mask[1] != 1 ||
22730           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22731         return SDValue();
22732
22733       Chain.push_back(V);
22734       continue;
22735
22736     case X86ISD::PSHUFHW:
22737       // Check that the high words (being shuffled) are the identity in the
22738       // dword shuffle, and the low words are self-contained.
22739       if (Mask[2] != 2 || Mask[3] != 3 ||
22740           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22741         return SDValue();
22742
22743       Chain.push_back(V);
22744       continue;
22745
22746     case X86ISD::UNPCKL:
22747     case X86ISD::UNPCKH:
22748       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22749       // shuffle into a preceding word shuffle.
22750       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
22751           V.getSimpleValueType().getVectorElementType() != MVT::i16)
22752         return SDValue();
22753
22754       // Search for a half-shuffle which we can combine with.
22755       unsigned CombineOp =
22756           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22757       if (V.getOperand(0) != V.getOperand(1) ||
22758           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22759         return SDValue();
22760       Chain.push_back(V);
22761       V = V.getOperand(0);
22762       do {
22763         switch (V.getOpcode()) {
22764         default:
22765           return SDValue(); // Nothing to combine.
22766
22767         case X86ISD::PSHUFLW:
22768         case X86ISD::PSHUFHW:
22769           if (V.getOpcode() == CombineOp)
22770             break;
22771
22772           Chain.push_back(V);
22773
22774           // Fallthrough!
22775         case ISD::BITCAST:
22776           V = V.getOperand(0);
22777           continue;
22778         }
22779         break;
22780       } while (V.hasOneUse());
22781       break;
22782     }
22783     // Break out of the loop if we break out of the switch.
22784     break;
22785   }
22786
22787   if (!V.hasOneUse())
22788     // We fell out of the loop without finding a viable combining instruction.
22789     return SDValue();
22790
22791   // Merge this node's mask and our incoming mask.
22792   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22793   for (int &M : Mask)
22794     M = VMask[M];
22795   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22796                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22797
22798   // Rebuild the chain around this new shuffle.
22799   while (!Chain.empty()) {
22800     SDValue W = Chain.pop_back_val();
22801
22802     if (V.getValueType() != W.getOperand(0).getValueType())
22803       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22804
22805     switch (W.getOpcode()) {
22806     default:
22807       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22808
22809     case X86ISD::UNPCKL:
22810     case X86ISD::UNPCKH:
22811       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22812       break;
22813
22814     case X86ISD::PSHUFD:
22815     case X86ISD::PSHUFLW:
22816     case X86ISD::PSHUFHW:
22817       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22818       break;
22819     }
22820   }
22821   if (V.getValueType() != N.getValueType())
22822     V = DAG.getBitcast(N.getValueType(), V);
22823
22824   // Return the new chain to replace N.
22825   return V;
22826 }
22827
22828 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22829 /// pshufhw.
22830 ///
22831 /// We walk up the chain, skipping shuffles of the other half and looking
22832 /// through shuffles which switch halves trying to find a shuffle of the same
22833 /// pair of dwords.
22834 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22835                                         SelectionDAG &DAG,
22836                                         TargetLowering::DAGCombinerInfo &DCI) {
22837   assert(
22838       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22839       "Called with something other than an x86 128-bit half shuffle!");
22840   SDLoc DL(N);
22841   unsigned CombineOpcode = N.getOpcode();
22842
22843   // Walk up a single-use chain looking for a combinable shuffle.
22844   SDValue V = N.getOperand(0);
22845   for (; V.hasOneUse(); V = V.getOperand(0)) {
22846     switch (V.getOpcode()) {
22847     default:
22848       return false; // Nothing combined!
22849
22850     case ISD::BITCAST:
22851       // Skip bitcasts as we always know the type for the target specific
22852       // instructions.
22853       continue;
22854
22855     case X86ISD::PSHUFLW:
22856     case X86ISD::PSHUFHW:
22857       if (V.getOpcode() == CombineOpcode)
22858         break;
22859
22860       // Other-half shuffles are no-ops.
22861       continue;
22862     }
22863     // Break out of the loop if we break out of the switch.
22864     break;
22865   }
22866
22867   if (!V.hasOneUse())
22868     // We fell out of the loop without finding a viable combining instruction.
22869     return false;
22870
22871   // Combine away the bottom node as its shuffle will be accumulated into
22872   // a preceding shuffle.
22873   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22874
22875   // Record the old value.
22876   SDValue Old = V;
22877
22878   // Merge this node's mask and our incoming mask (adjusted to account for all
22879   // the pshufd instructions encountered).
22880   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22881   for (int &M : Mask)
22882     M = VMask[M];
22883   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22884                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22885
22886   // Check that the shuffles didn't cancel each other out. If not, we need to
22887   // combine to the new one.
22888   if (Old != V)
22889     // Replace the combinable shuffle with the combined one, updating all users
22890     // so that we re-evaluate the chain here.
22891     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22892
22893   return true;
22894 }
22895
22896 /// \brief Try to combine x86 target specific shuffles.
22897 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22898                                            TargetLowering::DAGCombinerInfo &DCI,
22899                                            const X86Subtarget *Subtarget) {
22900   SDLoc DL(N);
22901   MVT VT = N.getSimpleValueType();
22902   SmallVector<int, 4> Mask;
22903
22904   switch (N.getOpcode()) {
22905   case X86ISD::PSHUFD:
22906   case X86ISD::PSHUFLW:
22907   case X86ISD::PSHUFHW:
22908     Mask = getPSHUFShuffleMask(N);
22909     assert(Mask.size() == 4);
22910     break;
22911   case X86ISD::UNPCKL: {
22912     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
22913     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
22914     // moves upper half elements into the lower half part. For example:
22915     //
22916     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
22917     //     undef:v16i8
22918     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
22919     //
22920     // will be combined to:
22921     //
22922     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
22923
22924     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
22925     // happen due to advanced instructions.
22926     if (!VT.is128BitVector())
22927       return SDValue();
22928
22929     auto Op0 = N.getOperand(0);
22930     auto Op1 = N.getOperand(1);
22931     if (Op0.getOpcode() == ISD::UNDEF &&
22932         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
22933       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
22934
22935       unsigned NumElts = VT.getVectorNumElements();
22936       SmallVector<int, 8> ExpectedMask(NumElts, -1);
22937       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
22938                 NumElts / 2);
22939
22940       auto ShufOp = Op1.getOperand(0);
22941       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
22942         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
22943     }
22944     return SDValue();
22945   }
22946   default:
22947     return SDValue();
22948   }
22949
22950   // Nuke no-op shuffles that show up after combining.
22951   if (isNoopShuffleMask(Mask))
22952     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22953
22954   // Look for simplifications involving one or two shuffle instructions.
22955   SDValue V = N.getOperand(0);
22956   switch (N.getOpcode()) {
22957   default:
22958     break;
22959   case X86ISD::PSHUFLW:
22960   case X86ISD::PSHUFHW:
22961     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
22962
22963     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22964       return SDValue(); // We combined away this shuffle, so we're done.
22965
22966     // See if this reduces to a PSHUFD which is no more expensive and can
22967     // combine with more operations. Note that it has to at least flip the
22968     // dwords as otherwise it would have been removed as a no-op.
22969     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22970       int DMask[] = {0, 1, 2, 3};
22971       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22972       DMask[DOffset + 0] = DOffset + 1;
22973       DMask[DOffset + 1] = DOffset + 0;
22974       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22975       V = DAG.getBitcast(DVT, V);
22976       DCI.AddToWorklist(V.getNode());
22977       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22978                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22979       DCI.AddToWorklist(V.getNode());
22980       return DAG.getBitcast(VT, V);
22981     }
22982
22983     // Look for shuffle patterns which can be implemented as a single unpack.
22984     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22985     // only works when we have a PSHUFD followed by two half-shuffles.
22986     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22987         (V.getOpcode() == X86ISD::PSHUFLW ||
22988          V.getOpcode() == X86ISD::PSHUFHW) &&
22989         V.getOpcode() != N.getOpcode() &&
22990         V.hasOneUse()) {
22991       SDValue D = V.getOperand(0);
22992       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22993         D = D.getOperand(0);
22994       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22995         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22996         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22997         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22998         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22999         int WordMask[8];
23000         for (int i = 0; i < 4; ++i) {
23001           WordMask[i + NOffset] = Mask[i] + NOffset;
23002           WordMask[i + VOffset] = VMask[i] + VOffset;
23003         }
23004         // Map the word mask through the DWord mask.
23005         int MappedMask[8];
23006         for (int i = 0; i < 8; ++i)
23007           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23008         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23009             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23010           // We can replace all three shuffles with an unpack.
23011           V = DAG.getBitcast(VT, D.getOperand(0));
23012           DCI.AddToWorklist(V.getNode());
23013           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23014                                                 : X86ISD::UNPCKH,
23015                              DL, VT, V, V);
23016         }
23017       }
23018     }
23019
23020     break;
23021
23022   case X86ISD::PSHUFD:
23023     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23024       return NewN;
23025
23026     break;
23027   }
23028
23029   return SDValue();
23030 }
23031
23032 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23033 ///
23034 /// We combine this directly on the abstract vector shuffle nodes so it is
23035 /// easier to generically match. We also insert dummy vector shuffle nodes for
23036 /// the operands which explicitly discard the lanes which are unused by this
23037 /// operation to try to flow through the rest of the combiner the fact that
23038 /// they're unused.
23039 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23040   SDLoc DL(N);
23041   EVT VT = N->getValueType(0);
23042
23043   // We only handle target-independent shuffles.
23044   // FIXME: It would be easy and harmless to use the target shuffle mask
23045   // extraction tool to support more.
23046   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23047     return SDValue();
23048
23049   auto *SVN = cast<ShuffleVectorSDNode>(N);
23050   ArrayRef<int> Mask = SVN->getMask();
23051   SDValue V1 = N->getOperand(0);
23052   SDValue V2 = N->getOperand(1);
23053
23054   // We require the first shuffle operand to be the SUB node, and the second to
23055   // be the ADD node.
23056   // FIXME: We should support the commuted patterns.
23057   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
23058     return SDValue();
23059
23060   // If there are other uses of these operations we can't fold them.
23061   if (!V1->hasOneUse() || !V2->hasOneUse())
23062     return SDValue();
23063
23064   // Ensure that both operations have the same operands. Note that we can
23065   // commute the FADD operands.
23066   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23067   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23068       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23069     return SDValue();
23070
23071   // We're looking for blends between FADD and FSUB nodes. We insist on these
23072   // nodes being lined up in a specific expected pattern.
23073   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23074         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23075         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23076     return SDValue();
23077
23078   // Only specific types are legal at this point, assert so we notice if and
23079   // when these change.
23080   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23081           VT == MVT::v4f64) &&
23082          "Unknown vector type encountered!");
23083
23084   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23085 }
23086
23087 /// PerformShuffleCombine - Performs several different shuffle combines.
23088 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23089                                      TargetLowering::DAGCombinerInfo &DCI,
23090                                      const X86Subtarget *Subtarget) {
23091   SDLoc dl(N);
23092   SDValue N0 = N->getOperand(0);
23093   SDValue N1 = N->getOperand(1);
23094   EVT VT = N->getValueType(0);
23095
23096   // Don't create instructions with illegal types after legalize types has run.
23097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23098   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23099     return SDValue();
23100
23101   // If we have legalized the vector types, look for blends of FADD and FSUB
23102   // nodes that we can fuse into an ADDSUB node.
23103   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23104     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23105       return AddSub;
23106
23107   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23108   if (Subtarget->hasFp256() && VT.is256BitVector() &&
23109       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23110     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23111
23112   // During Type Legalization, when promoting illegal vector types,
23113   // the backend might introduce new shuffle dag nodes and bitcasts.
23114   //
23115   // This code performs the following transformation:
23116   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23117   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23118   //
23119   // We do this only if both the bitcast and the BINOP dag nodes have
23120   // one use. Also, perform this transformation only if the new binary
23121   // operation is legal. This is to avoid introducing dag nodes that
23122   // potentially need to be further expanded (or custom lowered) into a
23123   // less optimal sequence of dag nodes.
23124   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23125       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23126       N0.getOpcode() == ISD::BITCAST) {
23127     SDValue BC0 = N0.getOperand(0);
23128     EVT SVT = BC0.getValueType();
23129     unsigned Opcode = BC0.getOpcode();
23130     unsigned NumElts = VT.getVectorNumElements();
23131
23132     if (BC0.hasOneUse() && SVT.isVector() &&
23133         SVT.getVectorNumElements() * 2 == NumElts &&
23134         TLI.isOperationLegal(Opcode, VT)) {
23135       bool CanFold = false;
23136       switch (Opcode) {
23137       default : break;
23138       case ISD::ADD :
23139       case ISD::FADD :
23140       case ISD::SUB :
23141       case ISD::FSUB :
23142       case ISD::MUL :
23143       case ISD::FMUL :
23144         CanFold = true;
23145       }
23146
23147       unsigned SVTNumElts = SVT.getVectorNumElements();
23148       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23149       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23150         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23151       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23152         CanFold = SVOp->getMaskElt(i) < 0;
23153
23154       if (CanFold) {
23155         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23156         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23157         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23158         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23159       }
23160     }
23161   }
23162
23163   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23164   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23165   // consecutive, non-overlapping, and in the right order.
23166   SmallVector<SDValue, 16> Elts;
23167   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23168     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23169
23170   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23171     return LD;
23172
23173   if (isTargetShuffle(N->getOpcode())) {
23174     SDValue Shuffle =
23175         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23176     if (Shuffle.getNode())
23177       return Shuffle;
23178
23179     // Try recursively combining arbitrary sequences of x86 shuffle
23180     // instructions into higher-order shuffles. We do this after combining
23181     // specific PSHUF instruction sequences into their minimal form so that we
23182     // can evaluate how many specialized shuffle instructions are involved in
23183     // a particular chain.
23184     SmallVector<int, 1> NonceMask; // Just a placeholder.
23185     NonceMask.push_back(0);
23186     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23187                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23188                                       DCI, Subtarget))
23189       return SDValue(); // This routine will use CombineTo to replace N.
23190   }
23191
23192   return SDValue();
23193 }
23194
23195 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23196 /// specific shuffle of a load can be folded into a single element load.
23197 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23198 /// shuffles have been custom lowered so we need to handle those here.
23199 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23200                                          TargetLowering::DAGCombinerInfo &DCI) {
23201   if (DCI.isBeforeLegalizeOps())
23202     return SDValue();
23203
23204   SDValue InVec = N->getOperand(0);
23205   SDValue EltNo = N->getOperand(1);
23206
23207   if (!isa<ConstantSDNode>(EltNo))
23208     return SDValue();
23209
23210   EVT OriginalVT = InVec.getValueType();
23211
23212   if (InVec.getOpcode() == ISD::BITCAST) {
23213     // Don't duplicate a load with other uses.
23214     if (!InVec.hasOneUse())
23215       return SDValue();
23216     EVT BCVT = InVec.getOperand(0).getValueType();
23217     if (!BCVT.isVector() ||
23218         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23219       return SDValue();
23220     InVec = InVec.getOperand(0);
23221   }
23222
23223   EVT CurrentVT = InVec.getValueType();
23224
23225   if (!isTargetShuffle(InVec.getOpcode()))
23226     return SDValue();
23227
23228   // Don't duplicate a load with other uses.
23229   if (!InVec.hasOneUse())
23230     return SDValue();
23231
23232   SmallVector<int, 16> ShuffleMask;
23233   bool UnaryShuffle;
23234   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23235                             ShuffleMask, UnaryShuffle))
23236     return SDValue();
23237
23238   // Select the input vector, guarding against out of range extract vector.
23239   unsigned NumElems = CurrentVT.getVectorNumElements();
23240   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23241   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23242   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23243                                          : InVec.getOperand(1);
23244
23245   // If inputs to shuffle are the same for both ops, then allow 2 uses
23246   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23247                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23248
23249   if (LdNode.getOpcode() == ISD::BITCAST) {
23250     // Don't duplicate a load with other uses.
23251     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23252       return SDValue();
23253
23254     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23255     LdNode = LdNode.getOperand(0);
23256   }
23257
23258   if (!ISD::isNormalLoad(LdNode.getNode()))
23259     return SDValue();
23260
23261   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23262
23263   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23264     return SDValue();
23265
23266   EVT EltVT = N->getValueType(0);
23267   // If there's a bitcast before the shuffle, check if the load type and
23268   // alignment is valid.
23269   unsigned Align = LN0->getAlignment();
23270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23271   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23272       EltVT.getTypeForEVT(*DAG.getContext()));
23273
23274   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23275     return SDValue();
23276
23277   // All checks match so transform back to vector_shuffle so that DAG combiner
23278   // can finish the job
23279   SDLoc dl(N);
23280
23281   // Create shuffle node taking into account the case that its a unary shuffle
23282   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23283                                    : InVec.getOperand(1);
23284   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23285                                  InVec.getOperand(0), Shuffle,
23286                                  &ShuffleMask[0]);
23287   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23288   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23289                      EltNo);
23290 }
23291
23292 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23293                                      const X86Subtarget *Subtarget) {
23294   SDValue N0 = N->getOperand(0);
23295   EVT VT = N->getValueType(0);
23296
23297   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23298   // special and don't usually play with other vector types, it's better to
23299   // handle them early to be sure we emit efficient code by avoiding
23300   // store-load conversions.
23301   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23302       N0.getValueType() == MVT::v2i32 &&
23303       isa<ConstantSDNode>(N0.getOperand(1))) {
23304     SDValue N00 = N0->getOperand(0);
23305     if (N0.getConstantOperandVal(1) == 0 && N00.getValueType() == MVT::i32)
23306       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23307   }
23308
23309   // Convert a bitcasted integer logic operation that has one bitcasted
23310   // floating-point operand and one constant operand into a floating-point
23311   // logic operation. This may create a load of the constant, but that is
23312   // cheaper than materializing the constant in an integer register and
23313   // transferring it to an SSE register or transferring the SSE operand to
23314   // integer register and back.
23315   unsigned FPOpcode;
23316   switch (N0.getOpcode()) {
23317     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23318     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23319     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23320     default: return SDValue();
23321   }
23322   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23323        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23324       isa<ConstantSDNode>(N0.getOperand(1)) &&
23325       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23326       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23327     SDValue N000 = N0.getOperand(0).getOperand(0);
23328     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23329     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23330   }
23331
23332   return SDValue();
23333 }
23334
23335 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23336 /// generation and convert it from being a bunch of shuffles and extracts
23337 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23338 /// storing the value and loading scalars back, while for x64 we should
23339 /// use 64-bit extracts and shifts.
23340 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23341                                          TargetLowering::DAGCombinerInfo &DCI) {
23342   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23343     return NewOp;
23344
23345   SDValue InputVector = N->getOperand(0);
23346   SDLoc dl(InputVector);
23347   // Detect mmx to i32 conversion through a v2i32 elt extract.
23348   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23349       N->getValueType(0) == MVT::i32 &&
23350       InputVector.getValueType() == MVT::v2i32) {
23351
23352     // The bitcast source is a direct mmx result.
23353     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23354     if (MMXSrc.getValueType() == MVT::x86mmx)
23355       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23356                          N->getValueType(0),
23357                          InputVector.getNode()->getOperand(0));
23358
23359     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23360     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23361         MMXSrc.getValueType() == MVT::i64) {
23362       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23363       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23364           MMXSrcOp.getValueType() == MVT::v1i64 &&
23365           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23366         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23367                            N->getValueType(0), MMXSrcOp.getOperand(0));
23368     }
23369   }
23370
23371   EVT VT = N->getValueType(0);
23372
23373   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23374       InputVector.getOpcode() == ISD::BITCAST &&
23375       isa<ConstantSDNode>(InputVector.getOperand(0))) {
23376     uint64_t ExtractedElt =
23377         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23378     uint64_t InputValue =
23379         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23380     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23381     return DAG.getConstant(Res, dl, MVT::i1);
23382   }
23383   // Only operate on vectors of 4 elements, where the alternative shuffling
23384   // gets to be more expensive.
23385   if (InputVector.getValueType() != MVT::v4i32)
23386     return SDValue();
23387
23388   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23389   // single use which is a sign-extend or zero-extend, and all elements are
23390   // used.
23391   SmallVector<SDNode *, 4> Uses;
23392   unsigned ExtractedElements = 0;
23393   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23394        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23395     if (UI.getUse().getResNo() != InputVector.getResNo())
23396       return SDValue();
23397
23398     SDNode *Extract = *UI;
23399     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23400       return SDValue();
23401
23402     if (Extract->getValueType(0) != MVT::i32)
23403       return SDValue();
23404     if (!Extract->hasOneUse())
23405       return SDValue();
23406     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23407         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23408       return SDValue();
23409     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23410       return SDValue();
23411
23412     // Record which element was extracted.
23413     ExtractedElements |=
23414       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23415
23416     Uses.push_back(Extract);
23417   }
23418
23419   // If not all the elements were used, this may not be worthwhile.
23420   if (ExtractedElements != 15)
23421     return SDValue();
23422
23423   // Ok, we've now decided to do the transformation.
23424   // If 64-bit shifts are legal, use the extract-shift sequence,
23425   // otherwise bounce the vector off the cache.
23426   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23427   SDValue Vals[4];
23428
23429   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23430     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23431     auto &DL = DAG.getDataLayout();
23432     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23433     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23434       DAG.getConstant(0, dl, VecIdxTy));
23435     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23436       DAG.getConstant(1, dl, VecIdxTy));
23437
23438     SDValue ShAmt = DAG.getConstant(
23439         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23440     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23441     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23442       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23443     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23444     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23445       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23446   } else {
23447     // Store the value to a temporary stack slot.
23448     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23449     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23450       MachinePointerInfo(), false, false, 0);
23451
23452     EVT ElementType = InputVector.getValueType().getVectorElementType();
23453     unsigned EltSize = ElementType.getSizeInBits() / 8;
23454
23455     // Replace each use (extract) with a load of the appropriate element.
23456     for (unsigned i = 0; i < 4; ++i) {
23457       uint64_t Offset = EltSize * i;
23458       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23459       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23460
23461       SDValue ScalarAddr =
23462           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23463
23464       // Load the scalar.
23465       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23466                             ScalarAddr, MachinePointerInfo(),
23467                             false, false, false, 0);
23468
23469     }
23470   }
23471
23472   // Replace the extracts
23473   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23474     UE = Uses.end(); UI != UE; ++UI) {
23475     SDNode *Extract = *UI;
23476
23477     SDValue Idx = Extract->getOperand(1);
23478     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23479     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23480   }
23481
23482   // The replacement was made in place; don't return anything.
23483   return SDValue();
23484 }
23485
23486 static SDValue
23487 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23488                                       const X86Subtarget *Subtarget) {
23489   SDLoc dl(N);
23490   SDValue Cond = N->getOperand(0);
23491   SDValue LHS = N->getOperand(1);
23492   SDValue RHS = N->getOperand(2);
23493
23494   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23495     SDValue CondSrc = Cond->getOperand(0);
23496     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23497       Cond = CondSrc->getOperand(0);
23498   }
23499
23500   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23501     return SDValue();
23502
23503   // A vselect where all conditions and data are constants can be optimized into
23504   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23505   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23506       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23507     return SDValue();
23508
23509   unsigned MaskValue = 0;
23510   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23511     return SDValue();
23512
23513   MVT VT = N->getSimpleValueType(0);
23514   unsigned NumElems = VT.getVectorNumElements();
23515   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23516   for (unsigned i = 0; i < NumElems; ++i) {
23517     // Be sure we emit undef where we can.
23518     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23519       ShuffleMask[i] = -1;
23520     else
23521       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23522   }
23523
23524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23525   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23526     return SDValue();
23527   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23528 }
23529
23530 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23531 /// nodes.
23532 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23533                                     TargetLowering::DAGCombinerInfo &DCI,
23534                                     const X86Subtarget *Subtarget) {
23535   SDLoc DL(N);
23536   SDValue Cond = N->getOperand(0);
23537   // Get the LHS/RHS of the select.
23538   SDValue LHS = N->getOperand(1);
23539   SDValue RHS = N->getOperand(2);
23540   EVT VT = LHS.getValueType();
23541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23542
23543   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23544   // instructions match the semantics of the common C idiom x<y?x:y but not
23545   // x<=y?x:y, because of how they handle negative zero (which can be
23546   // ignored in unsafe-math mode).
23547   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23548   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23549       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23550       (Subtarget->hasSSE2() ||
23551        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23552     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23553
23554     unsigned Opcode = 0;
23555     // Check for x CC y ? x : y.
23556     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23557         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23558       switch (CC) {
23559       default: break;
23560       case ISD::SETULT:
23561         // Converting this to a min would handle NaNs incorrectly, and swapping
23562         // the operands would cause it to handle comparisons between positive
23563         // and negative zero incorrectly.
23564         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23565           if (!DAG.getTarget().Options.UnsafeFPMath &&
23566               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23567             break;
23568           std::swap(LHS, RHS);
23569         }
23570         Opcode = X86ISD::FMIN;
23571         break;
23572       case ISD::SETOLE:
23573         // Converting this to a min would handle comparisons between positive
23574         // and negative zero incorrectly.
23575         if (!DAG.getTarget().Options.UnsafeFPMath &&
23576             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23577           break;
23578         Opcode = X86ISD::FMIN;
23579         break;
23580       case ISD::SETULE:
23581         // Converting this to a min would handle both negative zeros and NaNs
23582         // incorrectly, but we can swap the operands to fix both.
23583         std::swap(LHS, RHS);
23584       case ISD::SETOLT:
23585       case ISD::SETLT:
23586       case ISD::SETLE:
23587         Opcode = X86ISD::FMIN;
23588         break;
23589
23590       case ISD::SETOGE:
23591         // Converting this to a max would handle comparisons between positive
23592         // and negative zero incorrectly.
23593         if (!DAG.getTarget().Options.UnsafeFPMath &&
23594             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23595           break;
23596         Opcode = X86ISD::FMAX;
23597         break;
23598       case ISD::SETUGT:
23599         // Converting this to a max would handle NaNs incorrectly, and swapping
23600         // the operands would cause it to handle comparisons between positive
23601         // and negative zero incorrectly.
23602         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23603           if (!DAG.getTarget().Options.UnsafeFPMath &&
23604               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23605             break;
23606           std::swap(LHS, RHS);
23607         }
23608         Opcode = X86ISD::FMAX;
23609         break;
23610       case ISD::SETUGE:
23611         // Converting this to a max would handle both negative zeros and NaNs
23612         // incorrectly, but we can swap the operands to fix both.
23613         std::swap(LHS, RHS);
23614       case ISD::SETOGT:
23615       case ISD::SETGT:
23616       case ISD::SETGE:
23617         Opcode = X86ISD::FMAX;
23618         break;
23619       }
23620     // Check for x CC y ? y : x -- a min/max with reversed arms.
23621     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23622                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23623       switch (CC) {
23624       default: break;
23625       case ISD::SETOGE:
23626         // Converting this to a min would handle comparisons between positive
23627         // and negative zero incorrectly, and swapping the operands would
23628         // cause it to handle NaNs incorrectly.
23629         if (!DAG.getTarget().Options.UnsafeFPMath &&
23630             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23631           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23632             break;
23633           std::swap(LHS, RHS);
23634         }
23635         Opcode = X86ISD::FMIN;
23636         break;
23637       case ISD::SETUGT:
23638         // Converting this to a min would handle NaNs incorrectly.
23639         if (!DAG.getTarget().Options.UnsafeFPMath &&
23640             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23641           break;
23642         Opcode = X86ISD::FMIN;
23643         break;
23644       case ISD::SETUGE:
23645         // Converting this to a min would handle both negative zeros and NaNs
23646         // incorrectly, but we can swap the operands to fix both.
23647         std::swap(LHS, RHS);
23648       case ISD::SETOGT:
23649       case ISD::SETGT:
23650       case ISD::SETGE:
23651         Opcode = X86ISD::FMIN;
23652         break;
23653
23654       case ISD::SETULT:
23655         // Converting this to a max would handle NaNs incorrectly.
23656         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23657           break;
23658         Opcode = X86ISD::FMAX;
23659         break;
23660       case ISD::SETOLE:
23661         // Converting this to a max would handle comparisons between positive
23662         // and negative zero incorrectly, and swapping the operands would
23663         // cause it to handle NaNs incorrectly.
23664         if (!DAG.getTarget().Options.UnsafeFPMath &&
23665             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23666           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23667             break;
23668           std::swap(LHS, RHS);
23669         }
23670         Opcode = X86ISD::FMAX;
23671         break;
23672       case ISD::SETULE:
23673         // Converting this to a max would handle both negative zeros and NaNs
23674         // incorrectly, but we can swap the operands to fix both.
23675         std::swap(LHS, RHS);
23676       case ISD::SETOLT:
23677       case ISD::SETLT:
23678       case ISD::SETLE:
23679         Opcode = X86ISD::FMAX;
23680         break;
23681       }
23682     }
23683
23684     if (Opcode)
23685       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23686   }
23687
23688   EVT CondVT = Cond.getValueType();
23689   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23690       CondVT.getVectorElementType() == MVT::i1) {
23691     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23692     // lowering on KNL. In this case we convert it to
23693     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23694     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23695     // Since SKX these selects have a proper lowering.
23696     EVT OpVT = LHS.getValueType();
23697     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23698         (OpVT.getVectorElementType() == MVT::i8 ||
23699          OpVT.getVectorElementType() == MVT::i16) &&
23700         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23701       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23702       DCI.AddToWorklist(Cond.getNode());
23703       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23704     }
23705   }
23706   // If this is a select between two integer constants, try to do some
23707   // optimizations.
23708   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23709     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23710       // Don't do this for crazy integer types.
23711       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23712         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23713         // so that TrueC (the true value) is larger than FalseC.
23714         bool NeedsCondInvert = false;
23715
23716         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23717             // Efficiently invertible.
23718             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23719              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23720               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23721           NeedsCondInvert = true;
23722           std::swap(TrueC, FalseC);
23723         }
23724
23725         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23726         if (FalseC->getAPIntValue() == 0 &&
23727             TrueC->getAPIntValue().isPowerOf2()) {
23728           if (NeedsCondInvert) // Invert the condition if needed.
23729             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23730                                DAG.getConstant(1, DL, Cond.getValueType()));
23731
23732           // Zero extend the condition if needed.
23733           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23734
23735           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23736           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23737                              DAG.getConstant(ShAmt, DL, MVT::i8));
23738         }
23739
23740         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23741         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23742           if (NeedsCondInvert) // Invert the condition if needed.
23743             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23744                                DAG.getConstant(1, DL, Cond.getValueType()));
23745
23746           // Zero extend the condition if needed.
23747           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23748                              FalseC->getValueType(0), Cond);
23749           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23750                              SDValue(FalseC, 0));
23751         }
23752
23753         // Optimize cases that will turn into an LEA instruction.  This requires
23754         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23755         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23756           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23757           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23758
23759           bool isFastMultiplier = false;
23760           if (Diff < 10) {
23761             switch ((unsigned char)Diff) {
23762               default: break;
23763               case 1:  // result = add base, cond
23764               case 2:  // result = lea base(    , cond*2)
23765               case 3:  // result = lea base(cond, cond*2)
23766               case 4:  // result = lea base(    , cond*4)
23767               case 5:  // result = lea base(cond, cond*4)
23768               case 8:  // result = lea base(    , cond*8)
23769               case 9:  // result = lea base(cond, cond*8)
23770                 isFastMultiplier = true;
23771                 break;
23772             }
23773           }
23774
23775           if (isFastMultiplier) {
23776             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23777             if (NeedsCondInvert) // Invert the condition if needed.
23778               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23779                                  DAG.getConstant(1, DL, Cond.getValueType()));
23780
23781             // Zero extend the condition if needed.
23782             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23783                                Cond);
23784             // Scale the condition by the difference.
23785             if (Diff != 1)
23786               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23787                                  DAG.getConstant(Diff, DL,
23788                                                  Cond.getValueType()));
23789
23790             // Add the base if non-zero.
23791             if (FalseC->getAPIntValue() != 0)
23792               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23793                                  SDValue(FalseC, 0));
23794             return Cond;
23795           }
23796         }
23797       }
23798   }
23799
23800   // Canonicalize max and min:
23801   // (x > y) ? x : y -> (x >= y) ? x : y
23802   // (x < y) ? x : y -> (x <= y) ? x : y
23803   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23804   // the need for an extra compare
23805   // against zero. e.g.
23806   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23807   // subl   %esi, %edi
23808   // testl  %edi, %edi
23809   // movl   $0, %eax
23810   // cmovgl %edi, %eax
23811   // =>
23812   // xorl   %eax, %eax
23813   // subl   %esi, $edi
23814   // cmovsl %eax, %edi
23815   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23816       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23817       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23818     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23819     switch (CC) {
23820     default: break;
23821     case ISD::SETLT:
23822     case ISD::SETGT: {
23823       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23824       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23825                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23826       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23827     }
23828     }
23829   }
23830
23831   // Early exit check
23832   if (!TLI.isTypeLegal(VT))
23833     return SDValue();
23834
23835   // Match VSELECTs into subs with unsigned saturation.
23836   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23837       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23838       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23839        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23840     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23841
23842     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23843     // left side invert the predicate to simplify logic below.
23844     SDValue Other;
23845     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23846       Other = RHS;
23847       CC = ISD::getSetCCInverse(CC, true);
23848     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23849       Other = LHS;
23850     }
23851
23852     if (Other.getNode() && Other->getNumOperands() == 2 &&
23853         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23854       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23855       SDValue CondRHS = Cond->getOperand(1);
23856
23857       // Look for a general sub with unsigned saturation first.
23858       // x >= y ? x-y : 0 --> subus x, y
23859       // x >  y ? x-y : 0 --> subus x, y
23860       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23861           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23862         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23863
23864       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23865         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23866           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23867             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23868               // If the RHS is a constant we have to reverse the const
23869               // canonicalization.
23870               // x > C-1 ? x+-C : 0 --> subus x, C
23871               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23872                   CondRHSConst->getAPIntValue() ==
23873                       (-OpRHSConst->getAPIntValue() - 1))
23874                 return DAG.getNode(
23875                     X86ISD::SUBUS, DL, VT, OpLHS,
23876                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23877
23878           // Another special case: If C was a sign bit, the sub has been
23879           // canonicalized into a xor.
23880           // FIXME: Would it be better to use computeKnownBits to determine
23881           //        whether it's safe to decanonicalize the xor?
23882           // x s< 0 ? x^C : 0 --> subus x, C
23883           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23884               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23885               OpRHSConst->getAPIntValue().isSignBit())
23886             // Note that we have to rebuild the RHS constant here to ensure we
23887             // don't rely on particular values of undef lanes.
23888             return DAG.getNode(
23889                 X86ISD::SUBUS, DL, VT, OpLHS,
23890                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23891         }
23892     }
23893   }
23894
23895   // Simplify vector selection if condition value type matches vselect
23896   // operand type
23897   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23898     assert(Cond.getValueType().isVector() &&
23899            "vector select expects a vector selector!");
23900
23901     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23902     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23903
23904     // Try invert the condition if true value is not all 1s and false value
23905     // is not all 0s.
23906     if (!TValIsAllOnes && !FValIsAllZeros &&
23907         // Check if the selector will be produced by CMPP*/PCMP*
23908         Cond.getOpcode() == ISD::SETCC &&
23909         // Check if SETCC has already been promoted
23910         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23911             CondVT) {
23912       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23913       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23914
23915       if (TValIsAllZeros || FValIsAllOnes) {
23916         SDValue CC = Cond.getOperand(2);
23917         ISD::CondCode NewCC =
23918           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23919                                Cond.getOperand(0).getValueType().isInteger());
23920         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23921         std::swap(LHS, RHS);
23922         TValIsAllOnes = FValIsAllOnes;
23923         FValIsAllZeros = TValIsAllZeros;
23924       }
23925     }
23926
23927     if (TValIsAllOnes || FValIsAllZeros) {
23928       SDValue Ret;
23929
23930       if (TValIsAllOnes && FValIsAllZeros)
23931         Ret = Cond;
23932       else if (TValIsAllOnes)
23933         Ret =
23934             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23935       else if (FValIsAllZeros)
23936         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23937                           DAG.getBitcast(CondVT, LHS));
23938
23939       return DAG.getBitcast(VT, Ret);
23940     }
23941   }
23942
23943   // We should generate an X86ISD::BLENDI from a vselect if its argument
23944   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23945   // constants. This specific pattern gets generated when we split a
23946   // selector for a 512 bit vector in a machine without AVX512 (but with
23947   // 256-bit vectors), during legalization:
23948   //
23949   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23950   //
23951   // Iff we find this pattern and the build_vectors are built from
23952   // constants, we translate the vselect into a shuffle_vector that we
23953   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23954   if ((N->getOpcode() == ISD::VSELECT ||
23955        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23956       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23957     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23958     if (Shuffle.getNode())
23959       return Shuffle;
23960   }
23961
23962   // If this is a *dynamic* select (non-constant condition) and we can match
23963   // this node with one of the variable blend instructions, restructure the
23964   // condition so that the blends can use the high bit of each element and use
23965   // SimplifyDemandedBits to simplify the condition operand.
23966   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23967       !DCI.isBeforeLegalize() &&
23968       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23969     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
23970
23971     // Don't optimize vector selects that map to mask-registers.
23972     if (BitWidth == 1)
23973       return SDValue();
23974
23975     // We can only handle the cases where VSELECT is directly legal on the
23976     // subtarget. We custom lower VSELECT nodes with constant conditions and
23977     // this makes it hard to see whether a dynamic VSELECT will correctly
23978     // lower, so we both check the operation's status and explicitly handle the
23979     // cases where a *dynamic* blend will fail even though a constant-condition
23980     // blend could be custom lowered.
23981     // FIXME: We should find a better way to handle this class of problems.
23982     // Potentially, we should combine constant-condition vselect nodes
23983     // pre-legalization into shuffles and not mark as many types as custom
23984     // lowered.
23985     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23986       return SDValue();
23987     // FIXME: We don't support i16-element blends currently. We could and
23988     // should support them by making *all* the bits in the condition be set
23989     // rather than just the high bit and using an i8-element blend.
23990     if (VT.getVectorElementType() == MVT::i16)
23991       return SDValue();
23992     // Dynamic blending was only available from SSE4.1 onward.
23993     if (VT.is128BitVector() && !Subtarget->hasSSE41())
23994       return SDValue();
23995     // Byte blends are only available in AVX2
23996     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
23997       return SDValue();
23998
23999     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24000     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24001
24002     APInt KnownZero, KnownOne;
24003     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24004                                           DCI.isBeforeLegalizeOps());
24005     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24006         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24007                                  TLO)) {
24008       // If we changed the computation somewhere in the DAG, this change
24009       // will affect all users of Cond.
24010       // Make sure it is fine and update all the nodes so that we do not
24011       // use the generic VSELECT anymore. Otherwise, we may perform
24012       // wrong optimizations as we messed up with the actual expectation
24013       // for the vector boolean values.
24014       if (Cond != TLO.Old) {
24015         // Check all uses of that condition operand to check whether it will be
24016         // consumed by non-BLEND instructions, which may depend on all bits are
24017         // set properly.
24018         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24019              I != E; ++I)
24020           if (I->getOpcode() != ISD::VSELECT)
24021             // TODO: Add other opcodes eventually lowered into BLEND.
24022             return SDValue();
24023
24024         // Update all the users of the condition, before committing the change,
24025         // so that the VSELECT optimizations that expect the correct vector
24026         // boolean value will not be triggered.
24027         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24028              I != E; ++I)
24029           DAG.ReplaceAllUsesOfValueWith(
24030               SDValue(*I, 0),
24031               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24032                           Cond, I->getOperand(1), I->getOperand(2)));
24033         DCI.CommitTargetLoweringOpt(TLO);
24034         return SDValue();
24035       }
24036       // At this point, only Cond is changed. Change the condition
24037       // just for N to keep the opportunity to optimize all other
24038       // users their own way.
24039       DAG.ReplaceAllUsesOfValueWith(
24040           SDValue(N, 0),
24041           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24042                       TLO.New, N->getOperand(1), N->getOperand(2)));
24043       return SDValue();
24044     }
24045   }
24046
24047   return SDValue();
24048 }
24049
24050 // Check whether a boolean test is testing a boolean value generated by
24051 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24052 // code.
24053 //
24054 // Simplify the following patterns:
24055 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24056 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24057 // to (Op EFLAGS Cond)
24058 //
24059 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24060 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24061 // to (Op EFLAGS !Cond)
24062 //
24063 // where Op could be BRCOND or CMOV.
24064 //
24065 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24066   // Quit if not CMP and SUB with its value result used.
24067   if (Cmp.getOpcode() != X86ISD::CMP &&
24068       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24069       return SDValue();
24070
24071   // Quit if not used as a boolean value.
24072   if (CC != X86::COND_E && CC != X86::COND_NE)
24073     return SDValue();
24074
24075   // Check CMP operands. One of them should be 0 or 1 and the other should be
24076   // an SetCC or extended from it.
24077   SDValue Op1 = Cmp.getOperand(0);
24078   SDValue Op2 = Cmp.getOperand(1);
24079
24080   SDValue SetCC;
24081   const ConstantSDNode* C = nullptr;
24082   bool needOppositeCond = (CC == X86::COND_E);
24083   bool checkAgainstTrue = false; // Is it a comparison against 1?
24084
24085   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24086     SetCC = Op2;
24087   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24088     SetCC = Op1;
24089   else // Quit if all operands are not constants.
24090     return SDValue();
24091
24092   if (C->getZExtValue() == 1) {
24093     needOppositeCond = !needOppositeCond;
24094     checkAgainstTrue = true;
24095   } else if (C->getZExtValue() != 0)
24096     // Quit if the constant is neither 0 or 1.
24097     return SDValue();
24098
24099   bool truncatedToBoolWithAnd = false;
24100   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24101   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24102          SetCC.getOpcode() == ISD::TRUNCATE ||
24103          SetCC.getOpcode() == ISD::AND) {
24104     if (SetCC.getOpcode() == ISD::AND) {
24105       int OpIdx = -1;
24106       ConstantSDNode *CS;
24107       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
24108           CS->getZExtValue() == 1)
24109         OpIdx = 1;
24110       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
24111           CS->getZExtValue() == 1)
24112         OpIdx = 0;
24113       if (OpIdx == -1)
24114         break;
24115       SetCC = SetCC.getOperand(OpIdx);
24116       truncatedToBoolWithAnd = true;
24117     } else
24118       SetCC = SetCC.getOperand(0);
24119   }
24120
24121   switch (SetCC.getOpcode()) {
24122   case X86ISD::SETCC_CARRY:
24123     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24124     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24125     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24126     // truncated to i1 using 'and'.
24127     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24128       break;
24129     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24130            "Invalid use of SETCC_CARRY!");
24131     // FALL THROUGH
24132   case X86ISD::SETCC:
24133     // Set the condition code or opposite one if necessary.
24134     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24135     if (needOppositeCond)
24136       CC = X86::GetOppositeBranchCondition(CC);
24137     return SetCC.getOperand(1);
24138   case X86ISD::CMOV: {
24139     // Check whether false/true value has canonical one, i.e. 0 or 1.
24140     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24141     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24142     // Quit if true value is not a constant.
24143     if (!TVal)
24144       return SDValue();
24145     // Quit if false value is not a constant.
24146     if (!FVal) {
24147       SDValue Op = SetCC.getOperand(0);
24148       // Skip 'zext' or 'trunc' node.
24149       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24150           Op.getOpcode() == ISD::TRUNCATE)
24151         Op = Op.getOperand(0);
24152       // A special case for rdrand/rdseed, where 0 is set if false cond is
24153       // found.
24154       if ((Op.getOpcode() != X86ISD::RDRAND &&
24155            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24156         return SDValue();
24157     }
24158     // Quit if false value is not the constant 0 or 1.
24159     bool FValIsFalse = true;
24160     if (FVal && FVal->getZExtValue() != 0) {
24161       if (FVal->getZExtValue() != 1)
24162         return SDValue();
24163       // If FVal is 1, opposite cond is needed.
24164       needOppositeCond = !needOppositeCond;
24165       FValIsFalse = false;
24166     }
24167     // Quit if TVal is not the constant opposite of FVal.
24168     if (FValIsFalse && TVal->getZExtValue() != 1)
24169       return SDValue();
24170     if (!FValIsFalse && TVal->getZExtValue() != 0)
24171       return SDValue();
24172     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24173     if (needOppositeCond)
24174       CC = X86::GetOppositeBranchCondition(CC);
24175     return SetCC.getOperand(3);
24176   }
24177   }
24178
24179   return SDValue();
24180 }
24181
24182 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24183 /// Match:
24184 ///   (X86or (X86setcc) (X86setcc))
24185 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24186 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24187                                            X86::CondCode &CC1, SDValue &Flags,
24188                                            bool &isAnd) {
24189   if (Cond->getOpcode() == X86ISD::CMP) {
24190     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24191     if (!CondOp1C || !CondOp1C->isNullValue())
24192       return false;
24193
24194     Cond = Cond->getOperand(0);
24195   }
24196
24197   isAnd = false;
24198
24199   SDValue SetCC0, SetCC1;
24200   switch (Cond->getOpcode()) {
24201   default: return false;
24202   case ISD::AND:
24203   case X86ISD::AND:
24204     isAnd = true;
24205     // fallthru
24206   case ISD::OR:
24207   case X86ISD::OR:
24208     SetCC0 = Cond->getOperand(0);
24209     SetCC1 = Cond->getOperand(1);
24210     break;
24211   };
24212
24213   // Make sure we have SETCC nodes, using the same flags value.
24214   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24215       SetCC1.getOpcode() != X86ISD::SETCC ||
24216       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24217     return false;
24218
24219   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24220   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24221   Flags = SetCC0->getOperand(1);
24222   return true;
24223 }
24224
24225 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24226 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24227                                   TargetLowering::DAGCombinerInfo &DCI,
24228                                   const X86Subtarget *Subtarget) {
24229   SDLoc DL(N);
24230
24231   // If the flag operand isn't dead, don't touch this CMOV.
24232   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24233     return SDValue();
24234
24235   SDValue FalseOp = N->getOperand(0);
24236   SDValue TrueOp = N->getOperand(1);
24237   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24238   SDValue Cond = N->getOperand(3);
24239
24240   if (CC == X86::COND_E || CC == X86::COND_NE) {
24241     switch (Cond.getOpcode()) {
24242     default: break;
24243     case X86ISD::BSR:
24244     case X86ISD::BSF:
24245       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24246       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24247         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24248     }
24249   }
24250
24251   SDValue Flags;
24252
24253   Flags = checkBoolTestSetCCCombine(Cond, CC);
24254   if (Flags.getNode() &&
24255       // Extra check as FCMOV only supports a subset of X86 cond.
24256       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24257     SDValue Ops[] = { FalseOp, TrueOp,
24258                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24259     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24260   }
24261
24262   // If this is a select between two integer constants, try to do some
24263   // optimizations.  Note that the operands are ordered the opposite of SELECT
24264   // operands.
24265   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24266     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24267       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24268       // larger than FalseC (the false value).
24269       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24270         CC = X86::GetOppositeBranchCondition(CC);
24271         std::swap(TrueC, FalseC);
24272         std::swap(TrueOp, FalseOp);
24273       }
24274
24275       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24276       // This is efficient for any integer data type (including i8/i16) and
24277       // shift amount.
24278       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24279         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24280                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24281
24282         // Zero extend the condition if needed.
24283         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24284
24285         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24286         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24287                            DAG.getConstant(ShAmt, DL, MVT::i8));
24288         if (N->getNumValues() == 2)  // Dead flag value?
24289           return DCI.CombineTo(N, Cond, SDValue());
24290         return Cond;
24291       }
24292
24293       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24294       // for any integer data type, including i8/i16.
24295       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24296         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24297                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24298
24299         // Zero extend the condition if needed.
24300         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24301                            FalseC->getValueType(0), Cond);
24302         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24303                            SDValue(FalseC, 0));
24304
24305         if (N->getNumValues() == 2)  // Dead flag value?
24306           return DCI.CombineTo(N, Cond, SDValue());
24307         return Cond;
24308       }
24309
24310       // Optimize cases that will turn into an LEA instruction.  This requires
24311       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24312       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24313         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24314         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24315
24316         bool isFastMultiplier = false;
24317         if (Diff < 10) {
24318           switch ((unsigned char)Diff) {
24319           default: break;
24320           case 1:  // result = add base, cond
24321           case 2:  // result = lea base(    , cond*2)
24322           case 3:  // result = lea base(cond, cond*2)
24323           case 4:  // result = lea base(    , cond*4)
24324           case 5:  // result = lea base(cond, cond*4)
24325           case 8:  // result = lea base(    , cond*8)
24326           case 9:  // result = lea base(cond, cond*8)
24327             isFastMultiplier = true;
24328             break;
24329           }
24330         }
24331
24332         if (isFastMultiplier) {
24333           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24334           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24335                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24336           // Zero extend the condition if needed.
24337           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24338                              Cond);
24339           // Scale the condition by the difference.
24340           if (Diff != 1)
24341             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24342                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24343
24344           // Add the base if non-zero.
24345           if (FalseC->getAPIntValue() != 0)
24346             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24347                                SDValue(FalseC, 0));
24348           if (N->getNumValues() == 2)  // Dead flag value?
24349             return DCI.CombineTo(N, Cond, SDValue());
24350           return Cond;
24351         }
24352       }
24353     }
24354   }
24355
24356   // Handle these cases:
24357   //   (select (x != c), e, c) -> select (x != c), e, x),
24358   //   (select (x == c), c, e) -> select (x == c), x, e)
24359   // where the c is an integer constant, and the "select" is the combination
24360   // of CMOV and CMP.
24361   //
24362   // The rationale for this change is that the conditional-move from a constant
24363   // needs two instructions, however, conditional-move from a register needs
24364   // only one instruction.
24365   //
24366   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24367   //  some instruction-combining opportunities. This opt needs to be
24368   //  postponed as late as possible.
24369   //
24370   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24371     // the DCI.xxxx conditions are provided to postpone the optimization as
24372     // late as possible.
24373
24374     ConstantSDNode *CmpAgainst = nullptr;
24375     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24376         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24377         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24378
24379       if (CC == X86::COND_NE &&
24380           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24381         CC = X86::GetOppositeBranchCondition(CC);
24382         std::swap(TrueOp, FalseOp);
24383       }
24384
24385       if (CC == X86::COND_E &&
24386           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24387         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24388                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24389         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24390       }
24391     }
24392   }
24393
24394   // Fold and/or of setcc's to double CMOV:
24395   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24396   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24397   //
24398   // This combine lets us generate:
24399   //   cmovcc1 (jcc1 if we don't have CMOV)
24400   //   cmovcc2 (same)
24401   // instead of:
24402   //   setcc1
24403   //   setcc2
24404   //   and/or
24405   //   cmovne (jne if we don't have CMOV)
24406   // When we can't use the CMOV instruction, it might increase branch
24407   // mispredicts.
24408   // When we can use CMOV, or when there is no mispredict, this improves
24409   // throughput and reduces register pressure.
24410   //
24411   if (CC == X86::COND_NE) {
24412     SDValue Flags;
24413     X86::CondCode CC0, CC1;
24414     bool isAndSetCC;
24415     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24416       if (isAndSetCC) {
24417         std::swap(FalseOp, TrueOp);
24418         CC0 = X86::GetOppositeBranchCondition(CC0);
24419         CC1 = X86::GetOppositeBranchCondition(CC1);
24420       }
24421
24422       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24423         Flags};
24424       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24425       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24426       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24427       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24428       return CMOV;
24429     }
24430   }
24431
24432   return SDValue();
24433 }
24434
24435 /// PerformMulCombine - Optimize a single multiply with constant into two
24436 /// in order to implement it with two cheaper instructions, e.g.
24437 /// LEA + SHL, LEA + LEA.
24438 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24439                                  TargetLowering::DAGCombinerInfo &DCI) {
24440   // An imul is usually smaller than the alternative sequence.
24441   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24442     return SDValue();
24443
24444   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24445     return SDValue();
24446
24447   EVT VT = N->getValueType(0);
24448   if (VT != MVT::i64 && VT != MVT::i32)
24449     return SDValue();
24450
24451   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24452   if (!C)
24453     return SDValue();
24454   uint64_t MulAmt = C->getZExtValue();
24455   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24456     return SDValue();
24457
24458   uint64_t MulAmt1 = 0;
24459   uint64_t MulAmt2 = 0;
24460   if ((MulAmt % 9) == 0) {
24461     MulAmt1 = 9;
24462     MulAmt2 = MulAmt / 9;
24463   } else if ((MulAmt % 5) == 0) {
24464     MulAmt1 = 5;
24465     MulAmt2 = MulAmt / 5;
24466   } else if ((MulAmt % 3) == 0) {
24467     MulAmt1 = 3;
24468     MulAmt2 = MulAmt / 3;
24469   }
24470   if (MulAmt2 &&
24471       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24472     SDLoc DL(N);
24473
24474     if (isPowerOf2_64(MulAmt2) &&
24475         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24476       // If second multiplifer is pow2, issue it first. We want the multiply by
24477       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24478       // is an add.
24479       std::swap(MulAmt1, MulAmt2);
24480
24481     SDValue NewMul;
24482     if (isPowerOf2_64(MulAmt1))
24483       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24484                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24485     else
24486       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24487                            DAG.getConstant(MulAmt1, DL, VT));
24488
24489     if (isPowerOf2_64(MulAmt2))
24490       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24491                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24492     else
24493       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24494                            DAG.getConstant(MulAmt2, DL, VT));
24495
24496     // Do not add new nodes to DAG combiner worklist.
24497     DCI.CombineTo(N, NewMul, false);
24498   }
24499   return SDValue();
24500 }
24501
24502 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24503   SDValue N0 = N->getOperand(0);
24504   SDValue N1 = N->getOperand(1);
24505   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24506   EVT VT = N0.getValueType();
24507
24508   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24509   // since the result of setcc_c is all zero's or all ones.
24510   if (VT.isInteger() && !VT.isVector() &&
24511       N1C && N0.getOpcode() == ISD::AND &&
24512       N0.getOperand(1).getOpcode() == ISD::Constant) {
24513     SDValue N00 = N0.getOperand(0);
24514     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24515     APInt ShAmt = N1C->getAPIntValue();
24516     Mask = Mask.shl(ShAmt);
24517     bool MaskOK = false;
24518     // We can handle cases concerning bit-widening nodes containing setcc_c if
24519     // we carefully interrogate the mask to make sure we are semantics
24520     // preserving.
24521     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24522     // of the underlying setcc_c operation if the setcc_c was zero extended.
24523     // Consider the following example:
24524     //   zext(setcc_c)                 -> i32 0x0000FFFF
24525     //   c1                            -> i32 0x0000FFFF
24526     //   c2                            -> i32 0x00000001
24527     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24528     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24529     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24530       MaskOK = true;
24531     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24532                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24533       MaskOK = true;
24534     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24535                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24536                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24537       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24538     }
24539     if (MaskOK && Mask != 0) {
24540       SDLoc DL(N);
24541       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24542     }
24543   }
24544
24545   // Hardware support for vector shifts is sparse which makes us scalarize the
24546   // vector operations in many cases. Also, on sandybridge ADD is faster than
24547   // shl.
24548   // (shl V, 1) -> add V,V
24549   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24550     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24551       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24552       // We shift all of the values by one. In many cases we do not have
24553       // hardware support for this operation. This is better expressed as an ADD
24554       // of two values.
24555       if (N1SplatC->getAPIntValue() == 1)
24556         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24557     }
24558
24559   return SDValue();
24560 }
24561
24562 /// \brief Returns a vector of 0s if the node in input is a vector logical
24563 /// shift by a constant amount which is known to be bigger than or equal
24564 /// to the vector element size in bits.
24565 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24566                                       const X86Subtarget *Subtarget) {
24567   EVT VT = N->getValueType(0);
24568
24569   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24570       (!Subtarget->hasInt256() ||
24571        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24572     return SDValue();
24573
24574   SDValue Amt = N->getOperand(1);
24575   SDLoc DL(N);
24576   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24577     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24578       APInt ShiftAmt = AmtSplat->getAPIntValue();
24579       unsigned MaxAmount =
24580         VT.getSimpleVT().getVectorElementType().getSizeInBits();
24581
24582       // SSE2/AVX2 logical shifts always return a vector of 0s
24583       // if the shift amount is bigger than or equal to
24584       // the element size. The constant shift amount will be
24585       // encoded as a 8-bit immediate.
24586       if (ShiftAmt.trunc(8).uge(MaxAmount))
24587         return getZeroVector(VT, Subtarget, DAG, DL);
24588     }
24589
24590   return SDValue();
24591 }
24592
24593 /// PerformShiftCombine - Combine shifts.
24594 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24595                                    TargetLowering::DAGCombinerInfo &DCI,
24596                                    const X86Subtarget *Subtarget) {
24597   if (N->getOpcode() == ISD::SHL)
24598     if (SDValue V = PerformSHLCombine(N, DAG))
24599       return V;
24600
24601   // Try to fold this logical shift into a zero vector.
24602   if (N->getOpcode() != ISD::SRA)
24603     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24604       return V;
24605
24606   return SDValue();
24607 }
24608
24609 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24610 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24611 // and friends.  Likewise for OR -> CMPNEQSS.
24612 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24613                             TargetLowering::DAGCombinerInfo &DCI,
24614                             const X86Subtarget *Subtarget) {
24615   unsigned opcode;
24616
24617   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24618   // we're requiring SSE2 for both.
24619   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24620     SDValue N0 = N->getOperand(0);
24621     SDValue N1 = N->getOperand(1);
24622     SDValue CMP0 = N0->getOperand(1);
24623     SDValue CMP1 = N1->getOperand(1);
24624     SDLoc DL(N);
24625
24626     // The SETCCs should both refer to the same CMP.
24627     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24628       return SDValue();
24629
24630     SDValue CMP00 = CMP0->getOperand(0);
24631     SDValue CMP01 = CMP0->getOperand(1);
24632     EVT     VT    = CMP00.getValueType();
24633
24634     if (VT == MVT::f32 || VT == MVT::f64) {
24635       bool ExpectingFlags = false;
24636       // Check for any users that want flags:
24637       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24638            !ExpectingFlags && UI != UE; ++UI)
24639         switch (UI->getOpcode()) {
24640         default:
24641         case ISD::BR_CC:
24642         case ISD::BRCOND:
24643         case ISD::SELECT:
24644           ExpectingFlags = true;
24645           break;
24646         case ISD::CopyToReg:
24647         case ISD::SIGN_EXTEND:
24648         case ISD::ZERO_EXTEND:
24649         case ISD::ANY_EXTEND:
24650           break;
24651         }
24652
24653       if (!ExpectingFlags) {
24654         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24655         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24656
24657         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24658           X86::CondCode tmp = cc0;
24659           cc0 = cc1;
24660           cc1 = tmp;
24661         }
24662
24663         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24664             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24665           // FIXME: need symbolic constants for these magic numbers.
24666           // See X86ATTInstPrinter.cpp:printSSECC().
24667           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24668           if (Subtarget->hasAVX512()) {
24669             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24670                                          CMP01,
24671                                          DAG.getConstant(x86cc, DL, MVT::i8));
24672             if (N->getValueType(0) != MVT::i1)
24673               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24674                                  FSetCC);
24675             return FSetCC;
24676           }
24677           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24678                                               CMP00.getValueType(), CMP00, CMP01,
24679                                               DAG.getConstant(x86cc, DL,
24680                                                               MVT::i8));
24681
24682           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24683           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24684
24685           if (is64BitFP && !Subtarget->is64Bit()) {
24686             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24687             // 64-bit integer, since that's not a legal type. Since
24688             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24689             // bits, but can do this little dance to extract the lowest 32 bits
24690             // and work with those going forward.
24691             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24692                                            OnesOrZeroesF);
24693             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24694             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24695                                         Vector32, DAG.getIntPtrConstant(0, DL));
24696             IntVT = MVT::i32;
24697           }
24698
24699           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24700           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24701                                       DAG.getConstant(1, DL, IntVT));
24702           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24703                                               ANDed);
24704           return OneBitOfTruth;
24705         }
24706       }
24707     }
24708   }
24709   return SDValue();
24710 }
24711
24712 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24713 /// so it can be folded inside ANDNP.
24714 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24715   EVT VT = N->getValueType(0);
24716
24717   // Match direct AllOnes for 128 and 256-bit vectors
24718   if (ISD::isBuildVectorAllOnes(N))
24719     return true;
24720
24721   // Look through a bit convert.
24722   if (N->getOpcode() == ISD::BITCAST)
24723     N = N->getOperand(0).getNode();
24724
24725   // Sometimes the operand may come from a insert_subvector building a 256-bit
24726   // allones vector
24727   if (VT.is256BitVector() &&
24728       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24729     SDValue V1 = N->getOperand(0);
24730     SDValue V2 = N->getOperand(1);
24731
24732     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24733         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24734         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24735         ISD::isBuildVectorAllOnes(V2.getNode()))
24736       return true;
24737   }
24738
24739   return false;
24740 }
24741
24742 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24743 // register. In most cases we actually compare or select YMM-sized registers
24744 // and mixing the two types creates horrible code. This method optimizes
24745 // some of the transition sequences.
24746 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24747                                  TargetLowering::DAGCombinerInfo &DCI,
24748                                  const X86Subtarget *Subtarget) {
24749   EVT VT = N->getValueType(0);
24750   if (!VT.is256BitVector())
24751     return SDValue();
24752
24753   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24754           N->getOpcode() == ISD::ZERO_EXTEND ||
24755           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24756
24757   SDValue Narrow = N->getOperand(0);
24758   EVT NarrowVT = Narrow->getValueType(0);
24759   if (!NarrowVT.is128BitVector())
24760     return SDValue();
24761
24762   if (Narrow->getOpcode() != ISD::XOR &&
24763       Narrow->getOpcode() != ISD::AND &&
24764       Narrow->getOpcode() != ISD::OR)
24765     return SDValue();
24766
24767   SDValue N0  = Narrow->getOperand(0);
24768   SDValue N1  = Narrow->getOperand(1);
24769   SDLoc DL(Narrow);
24770
24771   // The Left side has to be a trunc.
24772   if (N0.getOpcode() != ISD::TRUNCATE)
24773     return SDValue();
24774
24775   // The type of the truncated inputs.
24776   EVT WideVT = N0->getOperand(0)->getValueType(0);
24777   if (WideVT != VT)
24778     return SDValue();
24779
24780   // The right side has to be a 'trunc' or a constant vector.
24781   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24782   ConstantSDNode *RHSConstSplat = nullptr;
24783   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24784     RHSConstSplat = RHSBV->getConstantSplatNode();
24785   if (!RHSTrunc && !RHSConstSplat)
24786     return SDValue();
24787
24788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24789
24790   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24791     return SDValue();
24792
24793   // Set N0 and N1 to hold the inputs to the new wide operation.
24794   N0 = N0->getOperand(0);
24795   if (RHSConstSplat) {
24796     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
24797                      SDValue(RHSConstSplat, 0));
24798     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24799     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24800   } else if (RHSTrunc) {
24801     N1 = N1->getOperand(0);
24802   }
24803
24804   // Generate the wide operation.
24805   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24806   unsigned Opcode = N->getOpcode();
24807   switch (Opcode) {
24808   case ISD::ANY_EXTEND:
24809     return Op;
24810   case ISD::ZERO_EXTEND: {
24811     unsigned InBits = NarrowVT.getScalarSizeInBits();
24812     APInt Mask = APInt::getAllOnesValue(InBits);
24813     Mask = Mask.zext(VT.getScalarSizeInBits());
24814     return DAG.getNode(ISD::AND, DL, VT,
24815                        Op, DAG.getConstant(Mask, DL, VT));
24816   }
24817   case ISD::SIGN_EXTEND:
24818     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24819                        Op, DAG.getValueType(NarrowVT));
24820   default:
24821     llvm_unreachable("Unexpected opcode");
24822   }
24823 }
24824
24825 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24826                                  TargetLowering::DAGCombinerInfo &DCI,
24827                                  const X86Subtarget *Subtarget) {
24828   SDValue N0 = N->getOperand(0);
24829   SDValue N1 = N->getOperand(1);
24830   SDLoc DL(N);
24831
24832   // A vector zext_in_reg may be represented as a shuffle,
24833   // feeding into a bitcast (this represents anyext) feeding into
24834   // an and with a mask.
24835   // We'd like to try to combine that into a shuffle with zero
24836   // plus a bitcast, removing the and.
24837   if (N0.getOpcode() != ISD::BITCAST ||
24838       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24839     return SDValue();
24840
24841   // The other side of the AND should be a splat of 2^C, where C
24842   // is the number of bits in the source type.
24843   if (N1.getOpcode() == ISD::BITCAST)
24844     N1 = N1.getOperand(0);
24845   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24846     return SDValue();
24847   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24848
24849   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24850   EVT SrcType = Shuffle->getValueType(0);
24851
24852   // We expect a single-source shuffle
24853   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24854     return SDValue();
24855
24856   unsigned SrcSize = SrcType.getScalarSizeInBits();
24857
24858   APInt SplatValue, SplatUndef;
24859   unsigned SplatBitSize;
24860   bool HasAnyUndefs;
24861   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24862                                 SplatBitSize, HasAnyUndefs))
24863     return SDValue();
24864
24865   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24866   // Make sure the splat matches the mask we expect
24867   if (SplatBitSize > ResSize ||
24868       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24869     return SDValue();
24870
24871   // Make sure the input and output size make sense
24872   if (SrcSize >= ResSize || ResSize % SrcSize)
24873     return SDValue();
24874
24875   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24876   // The number of u's between each two values depends on the ratio between
24877   // the source and dest type.
24878   unsigned ZextRatio = ResSize / SrcSize;
24879   bool IsZext = true;
24880   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24881     if (i % ZextRatio) {
24882       if (Shuffle->getMaskElt(i) > 0) {
24883         // Expected undef
24884         IsZext = false;
24885         break;
24886       }
24887     } else {
24888       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24889         // Expected element number
24890         IsZext = false;
24891         break;
24892       }
24893     }
24894   }
24895
24896   if (!IsZext)
24897     return SDValue();
24898
24899   // Ok, perform the transformation - replace the shuffle with
24900   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24901   // (instead of undef) where the k elements come from the zero vector.
24902   SmallVector<int, 8> Mask;
24903   unsigned NumElems = SrcType.getVectorNumElements();
24904   for (unsigned i = 0; i < NumElems; ++i)
24905     if (i % ZextRatio)
24906       Mask.push_back(NumElems);
24907     else
24908       Mask.push_back(i / ZextRatio);
24909
24910   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24911     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24912   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24913 }
24914
24915 /// If both input operands of a logic op are being cast from floating point
24916 /// types, try to convert this into a floating point logic node to avoid
24917 /// unnecessary moves from SSE to integer registers.
24918 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24919                                         const X86Subtarget *Subtarget) {
24920   unsigned FPOpcode = ISD::DELETED_NODE;
24921   if (N->getOpcode() == ISD::AND)
24922     FPOpcode = X86ISD::FAND;
24923   else if (N->getOpcode() == ISD::OR)
24924     FPOpcode = X86ISD::FOR;
24925   else if (N->getOpcode() == ISD::XOR)
24926     FPOpcode = X86ISD::FXOR;
24927
24928   assert(FPOpcode != ISD::DELETED_NODE &&
24929          "Unexpected input node for FP logic conversion");
24930
24931   EVT VT = N->getValueType(0);
24932   SDValue N0 = N->getOperand(0);
24933   SDValue N1 = N->getOperand(1);
24934   SDLoc DL(N);
24935   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24936       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24937        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24938     SDValue N00 = N0.getOperand(0);
24939     SDValue N10 = N1.getOperand(0);
24940     EVT N00Type = N00.getValueType();
24941     EVT N10Type = N10.getValueType();
24942     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24943       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24944       return DAG.getBitcast(VT, FPLogic);
24945     }
24946   }
24947   return SDValue();
24948 }
24949
24950 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24951                                  TargetLowering::DAGCombinerInfo &DCI,
24952                                  const X86Subtarget *Subtarget) {
24953   if (DCI.isBeforeLegalizeOps())
24954     return SDValue();
24955
24956   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24957     return Zext;
24958
24959   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24960     return R;
24961
24962   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24963     return FPLogic;
24964
24965   EVT VT = N->getValueType(0);
24966   SDValue N0 = N->getOperand(0);
24967   SDValue N1 = N->getOperand(1);
24968   SDLoc DL(N);
24969
24970   // Create BEXTR instructions
24971   // BEXTR is ((X >> imm) & (2**size-1))
24972   if (VT == MVT::i32 || VT == MVT::i64) {
24973     // Check for BEXTR.
24974     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24975         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24976       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24977       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24978       if (MaskNode && ShiftNode) {
24979         uint64_t Mask = MaskNode->getZExtValue();
24980         uint64_t Shift = ShiftNode->getZExtValue();
24981         if (isMask_64(Mask)) {
24982           uint64_t MaskSize = countPopulation(Mask);
24983           if (Shift + MaskSize <= VT.getSizeInBits())
24984             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24985                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24986                                                VT));
24987         }
24988       }
24989     } // BEXTR
24990
24991     return SDValue();
24992   }
24993
24994   // Want to form ANDNP nodes:
24995   // 1) In the hopes of then easily combining them with OR and AND nodes
24996   //    to form PBLEND/PSIGN.
24997   // 2) To match ANDN packed intrinsics
24998   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24999     return SDValue();
25000
25001   // Check LHS for vnot
25002   if (N0.getOpcode() == ISD::XOR &&
25003       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25004       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25005     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25006
25007   // Check RHS for vnot
25008   if (N1.getOpcode() == ISD::XOR &&
25009       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25010       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25011     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25012
25013   return SDValue();
25014 }
25015
25016 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25017                                 TargetLowering::DAGCombinerInfo &DCI,
25018                                 const X86Subtarget *Subtarget) {
25019   if (DCI.isBeforeLegalizeOps())
25020     return SDValue();
25021
25022   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25023     return R;
25024
25025   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25026     return FPLogic;
25027
25028   SDValue N0 = N->getOperand(0);
25029   SDValue N1 = N->getOperand(1);
25030   EVT VT = N->getValueType(0);
25031
25032   // look for psign/blend
25033   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25034     if (!Subtarget->hasSSSE3() ||
25035         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25036       return SDValue();
25037
25038     // Canonicalize pandn to RHS
25039     if (N0.getOpcode() == X86ISD::ANDNP)
25040       std::swap(N0, N1);
25041     // or (and (m, y), (pandn m, x))
25042     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25043       SDValue Mask = N1.getOperand(0);
25044       SDValue X    = N1.getOperand(1);
25045       SDValue Y;
25046       if (N0.getOperand(0) == Mask)
25047         Y = N0.getOperand(1);
25048       if (N0.getOperand(1) == Mask)
25049         Y = N0.getOperand(0);
25050
25051       // Check to see if the mask appeared in both the AND and ANDNP and
25052       if (!Y.getNode())
25053         return SDValue();
25054
25055       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25056       // Look through mask bitcast.
25057       if (Mask.getOpcode() == ISD::BITCAST)
25058         Mask = Mask.getOperand(0);
25059       if (X.getOpcode() == ISD::BITCAST)
25060         X = X.getOperand(0);
25061       if (Y.getOpcode() == ISD::BITCAST)
25062         Y = Y.getOperand(0);
25063
25064       EVT MaskVT = Mask.getValueType();
25065
25066       // Validate that the Mask operand is a vector sra node.
25067       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25068       // there is no psrai.b
25069       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25070       unsigned SraAmt = ~0;
25071       if (Mask.getOpcode() == ISD::SRA) {
25072         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25073           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25074             SraAmt = AmtConst->getZExtValue();
25075       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25076         SDValue SraC = Mask.getOperand(1);
25077         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25078       }
25079       if ((SraAmt + 1) != EltBits)
25080         return SDValue();
25081
25082       SDLoc DL(N);
25083
25084       // Now we know we at least have a plendvb with the mask val.  See if
25085       // we can form a psignb/w/d.
25086       // psign = x.type == y.type == mask.type && y = sub(0, x);
25087       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25088           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25089           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25090         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25091                "Unsupported VT for PSIGN");
25092         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25093         return DAG.getBitcast(VT, Mask);
25094       }
25095       // PBLENDVB only available on SSE 4.1
25096       if (!Subtarget->hasSSE41())
25097         return SDValue();
25098
25099       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25100
25101       X = DAG.getBitcast(BlendVT, X);
25102       Y = DAG.getBitcast(BlendVT, Y);
25103       Mask = DAG.getBitcast(BlendVT, Mask);
25104       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25105       return DAG.getBitcast(VT, Mask);
25106     }
25107   }
25108
25109   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25110     return SDValue();
25111
25112   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25113   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25114
25115   // SHLD/SHRD instructions have lower register pressure, but on some
25116   // platforms they have higher latency than the equivalent
25117   // series of shifts/or that would otherwise be generated.
25118   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25119   // have higher latencies and we are not optimizing for size.
25120   if (!OptForSize && Subtarget->isSHLDSlow())
25121     return SDValue();
25122
25123   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25124     std::swap(N0, N1);
25125   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25126     return SDValue();
25127   if (!N0.hasOneUse() || !N1.hasOneUse())
25128     return SDValue();
25129
25130   SDValue ShAmt0 = N0.getOperand(1);
25131   if (ShAmt0.getValueType() != MVT::i8)
25132     return SDValue();
25133   SDValue ShAmt1 = N1.getOperand(1);
25134   if (ShAmt1.getValueType() != MVT::i8)
25135     return SDValue();
25136   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25137     ShAmt0 = ShAmt0.getOperand(0);
25138   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25139     ShAmt1 = ShAmt1.getOperand(0);
25140
25141   SDLoc DL(N);
25142   unsigned Opc = X86ISD::SHLD;
25143   SDValue Op0 = N0.getOperand(0);
25144   SDValue Op1 = N1.getOperand(0);
25145   if (ShAmt0.getOpcode() == ISD::SUB) {
25146     Opc = X86ISD::SHRD;
25147     std::swap(Op0, Op1);
25148     std::swap(ShAmt0, ShAmt1);
25149   }
25150
25151   unsigned Bits = VT.getSizeInBits();
25152   if (ShAmt1.getOpcode() == ISD::SUB) {
25153     SDValue Sum = ShAmt1.getOperand(0);
25154     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25155       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25156       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25157         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25158       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25159         return DAG.getNode(Opc, DL, VT,
25160                            Op0, Op1,
25161                            DAG.getNode(ISD::TRUNCATE, DL,
25162                                        MVT::i8, ShAmt0));
25163     }
25164   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25165     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25166     if (ShAmt0C &&
25167         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25168       return DAG.getNode(Opc, DL, VT,
25169                          N0.getOperand(0), N1.getOperand(0),
25170                          DAG.getNode(ISD::TRUNCATE, DL,
25171                                        MVT::i8, ShAmt0));
25172   }
25173
25174   return SDValue();
25175 }
25176
25177 // Generate NEG and CMOV for integer abs.
25178 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25179   EVT VT = N->getValueType(0);
25180
25181   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25182   // 8-bit integer abs to NEG and CMOV.
25183   if (VT.isInteger() && VT.getSizeInBits() == 8)
25184     return SDValue();
25185
25186   SDValue N0 = N->getOperand(0);
25187   SDValue N1 = N->getOperand(1);
25188   SDLoc DL(N);
25189
25190   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25191   // and change it to SUB and CMOV.
25192   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25193       N0.getOpcode() == ISD::ADD &&
25194       N0.getOperand(1) == N1 &&
25195       N1.getOpcode() == ISD::SRA &&
25196       N1.getOperand(0) == N0.getOperand(0))
25197     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25198       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25199         // Generate SUB & CMOV.
25200         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25201                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25202
25203         SDValue Ops[] = { N0.getOperand(0), Neg,
25204                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25205                           SDValue(Neg.getNode(), 1) };
25206         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25207       }
25208   return SDValue();
25209 }
25210
25211 // Try to turn tests against the signbit in the form of:
25212 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25213 // into:
25214 //   SETGT(X, -1)
25215 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25216   // This is only worth doing if the output type is i8.
25217   if (N->getValueType(0) != MVT::i8)
25218     return SDValue();
25219
25220   SDValue N0 = N->getOperand(0);
25221   SDValue N1 = N->getOperand(1);
25222
25223   // We should be performing an xor against a truncated shift.
25224   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25225     return SDValue();
25226
25227   // Make sure we are performing an xor against one.
25228   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25229     return SDValue();
25230
25231   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25232   SDValue Shift = N0.getOperand(0);
25233   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25234     return SDValue();
25235
25236   // Make sure we are truncating from one of i16, i32 or i64.
25237   EVT ShiftTy = Shift.getValueType();
25238   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25239     return SDValue();
25240
25241   // Make sure the shift amount extracts the sign bit.
25242   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25243       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25244     return SDValue();
25245
25246   // Create a greater-than comparison against -1.
25247   // N.B. Using SETGE against 0 works but we want a canonical looking
25248   // comparison, using SETGT matches up with what TranslateX86CC.
25249   SDLoc DL(N);
25250   SDValue ShiftOp = Shift.getOperand(0);
25251   EVT ShiftOpTy = ShiftOp.getValueType();
25252   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25253                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25254   return Cond;
25255 }
25256
25257 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25258                                  TargetLowering::DAGCombinerInfo &DCI,
25259                                  const X86Subtarget *Subtarget) {
25260   if (DCI.isBeforeLegalizeOps())
25261     return SDValue();
25262
25263   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25264     return RV;
25265
25266   if (Subtarget->hasCMov())
25267     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25268       return RV;
25269
25270   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25271     return FPLogic;
25272
25273   return SDValue();
25274 }
25275
25276 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25277 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25278                                   TargetLowering::DAGCombinerInfo &DCI,
25279                                   const X86Subtarget *Subtarget) {
25280   LoadSDNode *Ld = cast<LoadSDNode>(N);
25281   EVT RegVT = Ld->getValueType(0);
25282   EVT MemVT = Ld->getMemoryVT();
25283   SDLoc dl(Ld);
25284   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25285
25286   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25287   // into two 16-byte operations.
25288   ISD::LoadExtType Ext = Ld->getExtensionType();
25289   bool Fast;
25290   unsigned AddressSpace = Ld->getAddressSpace();
25291   unsigned Alignment = Ld->getAlignment();
25292   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25293       Ext == ISD::NON_EXTLOAD &&
25294       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25295                              AddressSpace, Alignment, &Fast) && !Fast) {
25296     unsigned NumElems = RegVT.getVectorNumElements();
25297     if (NumElems < 2)
25298       return SDValue();
25299
25300     SDValue Ptr = Ld->getBasePtr();
25301     SDValue Increment =
25302         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25303
25304     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25305                                   NumElems/2);
25306     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25307                                 Ld->getPointerInfo(), Ld->isVolatile(),
25308                                 Ld->isNonTemporal(), Ld->isInvariant(),
25309                                 Alignment);
25310     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25311     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25312                                 Ld->getPointerInfo(), Ld->isVolatile(),
25313                                 Ld->isNonTemporal(), Ld->isInvariant(),
25314                                 std::min(16U, Alignment));
25315     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25316                              Load1.getValue(1),
25317                              Load2.getValue(1));
25318
25319     SDValue NewVec = DAG.getUNDEF(RegVT);
25320     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25321     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25322     return DCI.CombineTo(N, NewVec, TF, true);
25323   }
25324
25325   return SDValue();
25326 }
25327
25328 /// PerformMLOADCombine - Resolve extending loads
25329 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25330                                    TargetLowering::DAGCombinerInfo &DCI,
25331                                    const X86Subtarget *Subtarget) {
25332   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25333   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25334     return SDValue();
25335
25336   EVT VT = Mld->getValueType(0);
25337   unsigned NumElems = VT.getVectorNumElements();
25338   EVT LdVT = Mld->getMemoryVT();
25339   SDLoc dl(Mld);
25340
25341   assert(LdVT != VT && "Cannot extend to the same type");
25342   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25343   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25344   // From, To sizes and ElemCount must be pow of two
25345   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25346     "Unexpected size for extending masked load");
25347
25348   unsigned SizeRatio  = ToSz / FromSz;
25349   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25350
25351   // Create a type on which we perform the shuffle
25352   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25353           LdVT.getScalarType(), NumElems*SizeRatio);
25354   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25355
25356   // Convert Src0 value
25357   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25358   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25359     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25360     for (unsigned i = 0; i != NumElems; ++i)
25361       ShuffleVec[i] = i * SizeRatio;
25362
25363     // Can't shuffle using an illegal type.
25364     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25365            "WideVecVT should be legal");
25366     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25367                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25368   }
25369   // Prepare the new mask
25370   SDValue NewMask;
25371   SDValue Mask = Mld->getMask();
25372   if (Mask.getValueType() == VT) {
25373     // Mask and original value have the same type
25374     NewMask = DAG.getBitcast(WideVecVT, Mask);
25375     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25376     for (unsigned i = 0; i != NumElems; ++i)
25377       ShuffleVec[i] = i * SizeRatio;
25378     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25379       ShuffleVec[i] = NumElems*SizeRatio;
25380     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25381                                    DAG.getConstant(0, dl, WideVecVT),
25382                                    &ShuffleVec[0]);
25383   }
25384   else {
25385     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25386     unsigned WidenNumElts = NumElems*SizeRatio;
25387     unsigned MaskNumElts = VT.getVectorNumElements();
25388     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25389                                      WidenNumElts);
25390
25391     unsigned NumConcat = WidenNumElts / MaskNumElts;
25392     SmallVector<SDValue, 16> Ops(NumConcat);
25393     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25394     Ops[0] = Mask;
25395     for (unsigned i = 1; i != NumConcat; ++i)
25396       Ops[i] = ZeroVal;
25397
25398     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25399   }
25400
25401   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25402                                      Mld->getBasePtr(), NewMask, WideSrc0,
25403                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25404                                      ISD::NON_EXTLOAD);
25405   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25406   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25407 }
25408 /// PerformMSTORECombine - Resolve truncating stores
25409 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25410                                     const X86Subtarget *Subtarget) {
25411   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25412   if (!Mst->isTruncatingStore())
25413     return SDValue();
25414
25415   EVT VT = Mst->getValue().getValueType();
25416   unsigned NumElems = VT.getVectorNumElements();
25417   EVT StVT = Mst->getMemoryVT();
25418   SDLoc dl(Mst);
25419
25420   assert(StVT != VT && "Cannot truncate to the same type");
25421   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25422   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25423
25424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25425
25426   // The truncating store is legal in some cases. For example
25427   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25428   // are designated for truncate store.
25429   // In this case we don't need any further transformations.
25430   if (TLI.isTruncStoreLegal(VT, StVT))
25431     return SDValue();
25432
25433   // From, To sizes and ElemCount must be pow of two
25434   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25435     "Unexpected size for truncating masked store");
25436   // We are going to use the original vector elt for storing.
25437   // Accumulated smaller vector elements must be a multiple of the store size.
25438   assert (((NumElems * FromSz) % ToSz) == 0 &&
25439           "Unexpected ratio for truncating masked store");
25440
25441   unsigned SizeRatio  = FromSz / ToSz;
25442   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25443
25444   // Create a type on which we perform the shuffle
25445   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25446           StVT.getScalarType(), NumElems*SizeRatio);
25447
25448   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25449
25450   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25451   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25452   for (unsigned i = 0; i != NumElems; ++i)
25453     ShuffleVec[i] = i * SizeRatio;
25454
25455   // Can't shuffle using an illegal type.
25456   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25457          "WideVecVT should be legal");
25458
25459   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25460                                         DAG.getUNDEF(WideVecVT),
25461                                         &ShuffleVec[0]);
25462
25463   SDValue NewMask;
25464   SDValue Mask = Mst->getMask();
25465   if (Mask.getValueType() == VT) {
25466     // Mask and original value have the same type
25467     NewMask = DAG.getBitcast(WideVecVT, Mask);
25468     for (unsigned i = 0; i != NumElems; ++i)
25469       ShuffleVec[i] = i * SizeRatio;
25470     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25471       ShuffleVec[i] = NumElems*SizeRatio;
25472     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25473                                    DAG.getConstant(0, dl, WideVecVT),
25474                                    &ShuffleVec[0]);
25475   }
25476   else {
25477     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25478     unsigned WidenNumElts = NumElems*SizeRatio;
25479     unsigned MaskNumElts = VT.getVectorNumElements();
25480     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25481                                      WidenNumElts);
25482
25483     unsigned NumConcat = WidenNumElts / MaskNumElts;
25484     SmallVector<SDValue, 16> Ops(NumConcat);
25485     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25486     Ops[0] = Mask;
25487     for (unsigned i = 1; i != NumConcat; ++i)
25488       Ops[i] = ZeroVal;
25489
25490     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25491   }
25492
25493   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25494                             NewMask, StVT, Mst->getMemOperand(), false);
25495 }
25496 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25497 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25498                                    const X86Subtarget *Subtarget) {
25499   StoreSDNode *St = cast<StoreSDNode>(N);
25500   EVT VT = St->getValue().getValueType();
25501   EVT StVT = St->getMemoryVT();
25502   SDLoc dl(St);
25503   SDValue StoredVal = St->getOperand(1);
25504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25505
25506   // If we are saving a concatenation of two XMM registers and 32-byte stores
25507   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25508   bool Fast;
25509   unsigned AddressSpace = St->getAddressSpace();
25510   unsigned Alignment = St->getAlignment();
25511   if (VT.is256BitVector() && StVT == VT &&
25512       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25513                              AddressSpace, Alignment, &Fast) && !Fast) {
25514     unsigned NumElems = VT.getVectorNumElements();
25515     if (NumElems < 2)
25516       return SDValue();
25517
25518     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25519     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25520
25521     SDValue Stride =
25522         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25523     SDValue Ptr0 = St->getBasePtr();
25524     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25525
25526     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25527                                 St->getPointerInfo(), St->isVolatile(),
25528                                 St->isNonTemporal(), Alignment);
25529     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25530                                 St->getPointerInfo(), St->isVolatile(),
25531                                 St->isNonTemporal(),
25532                                 std::min(16U, Alignment));
25533     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25534   }
25535
25536   // Optimize trunc store (of multiple scalars) to shuffle and store.
25537   // First, pack all of the elements in one place. Next, store to memory
25538   // in fewer chunks.
25539   if (St->isTruncatingStore() && VT.isVector()) {
25540     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25541     unsigned NumElems = VT.getVectorNumElements();
25542     assert(StVT != VT && "Cannot truncate to the same type");
25543     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25544     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25545
25546     // The truncating store is legal in some cases. For example
25547     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25548     // are designated for truncate store.
25549     // In this case we don't need any further transformations.
25550     if (TLI.isTruncStoreLegal(VT, StVT))
25551       return SDValue();
25552
25553     // From, To sizes and ElemCount must be pow of two
25554     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25555     // We are going to use the original vector elt for storing.
25556     // Accumulated smaller vector elements must be a multiple of the store size.
25557     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25558
25559     unsigned SizeRatio  = FromSz / ToSz;
25560
25561     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25562
25563     // Create a type on which we perform the shuffle
25564     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25565             StVT.getScalarType(), NumElems*SizeRatio);
25566
25567     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25568
25569     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25570     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25571     for (unsigned i = 0; i != NumElems; ++i)
25572       ShuffleVec[i] = i * SizeRatio;
25573
25574     // Can't shuffle using an illegal type.
25575     if (!TLI.isTypeLegal(WideVecVT))
25576       return SDValue();
25577
25578     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25579                                          DAG.getUNDEF(WideVecVT),
25580                                          &ShuffleVec[0]);
25581     // At this point all of the data is stored at the bottom of the
25582     // register. We now need to save it to mem.
25583
25584     // Find the largest store unit
25585     MVT StoreType = MVT::i8;
25586     for (MVT Tp : MVT::integer_valuetypes()) {
25587       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25588         StoreType = Tp;
25589     }
25590
25591     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25592     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25593         (64 <= NumElems * ToSz))
25594       StoreType = MVT::f64;
25595
25596     // Bitcast the original vector into a vector of store-size units
25597     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25598             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25599     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25600     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25601     SmallVector<SDValue, 8> Chains;
25602     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25603                                         TLI.getPointerTy(DAG.getDataLayout()));
25604     SDValue Ptr = St->getBasePtr();
25605
25606     // Perform one or more big stores into memory.
25607     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25608       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25609                                    StoreType, ShuffWide,
25610                                    DAG.getIntPtrConstant(i, dl));
25611       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25612                                 St->getPointerInfo(), St->isVolatile(),
25613                                 St->isNonTemporal(), St->getAlignment());
25614       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25615       Chains.push_back(Ch);
25616     }
25617
25618     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25619   }
25620
25621   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25622   // the FP state in cases where an emms may be missing.
25623   // A preferable solution to the general problem is to figure out the right
25624   // places to insert EMMS.  This qualifies as a quick hack.
25625
25626   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25627   if (VT.getSizeInBits() != 64)
25628     return SDValue();
25629
25630   const Function *F = DAG.getMachineFunction().getFunction();
25631   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25632   bool F64IsLegal =
25633       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25634   if ((VT.isVector() ||
25635        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25636       isa<LoadSDNode>(St->getValue()) &&
25637       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25638       St->getChain().hasOneUse() && !St->isVolatile()) {
25639     SDNode* LdVal = St->getValue().getNode();
25640     LoadSDNode *Ld = nullptr;
25641     int TokenFactorIndex = -1;
25642     SmallVector<SDValue, 8> Ops;
25643     SDNode* ChainVal = St->getChain().getNode();
25644     // Must be a store of a load.  We currently handle two cases:  the load
25645     // is a direct child, and it's under an intervening TokenFactor.  It is
25646     // possible to dig deeper under nested TokenFactors.
25647     if (ChainVal == LdVal)
25648       Ld = cast<LoadSDNode>(St->getChain());
25649     else if (St->getValue().hasOneUse() &&
25650              ChainVal->getOpcode() == ISD::TokenFactor) {
25651       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25652         if (ChainVal->getOperand(i).getNode() == LdVal) {
25653           TokenFactorIndex = i;
25654           Ld = cast<LoadSDNode>(St->getValue());
25655         } else
25656           Ops.push_back(ChainVal->getOperand(i));
25657       }
25658     }
25659
25660     if (!Ld || !ISD::isNormalLoad(Ld))
25661       return SDValue();
25662
25663     // If this is not the MMX case, i.e. we are just turning i64 load/store
25664     // into f64 load/store, avoid the transformation if there are multiple
25665     // uses of the loaded value.
25666     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25667       return SDValue();
25668
25669     SDLoc LdDL(Ld);
25670     SDLoc StDL(N);
25671     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25672     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25673     // pair instead.
25674     if (Subtarget->is64Bit() || F64IsLegal) {
25675       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25676       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25677                                   Ld->getPointerInfo(), Ld->isVolatile(),
25678                                   Ld->isNonTemporal(), Ld->isInvariant(),
25679                                   Ld->getAlignment());
25680       SDValue NewChain = NewLd.getValue(1);
25681       if (TokenFactorIndex != -1) {
25682         Ops.push_back(NewChain);
25683         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25684       }
25685       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25686                           St->getPointerInfo(),
25687                           St->isVolatile(), St->isNonTemporal(),
25688                           St->getAlignment());
25689     }
25690
25691     // Otherwise, lower to two pairs of 32-bit loads / stores.
25692     SDValue LoAddr = Ld->getBasePtr();
25693     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25694                                  DAG.getConstant(4, LdDL, MVT::i32));
25695
25696     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25697                                Ld->getPointerInfo(),
25698                                Ld->isVolatile(), Ld->isNonTemporal(),
25699                                Ld->isInvariant(), Ld->getAlignment());
25700     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25701                                Ld->getPointerInfo().getWithOffset(4),
25702                                Ld->isVolatile(), Ld->isNonTemporal(),
25703                                Ld->isInvariant(),
25704                                MinAlign(Ld->getAlignment(), 4));
25705
25706     SDValue NewChain = LoLd.getValue(1);
25707     if (TokenFactorIndex != -1) {
25708       Ops.push_back(LoLd);
25709       Ops.push_back(HiLd);
25710       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25711     }
25712
25713     LoAddr = St->getBasePtr();
25714     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25715                          DAG.getConstant(4, StDL, MVT::i32));
25716
25717     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25718                                 St->getPointerInfo(),
25719                                 St->isVolatile(), St->isNonTemporal(),
25720                                 St->getAlignment());
25721     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25722                                 St->getPointerInfo().getWithOffset(4),
25723                                 St->isVolatile(),
25724                                 St->isNonTemporal(),
25725                                 MinAlign(St->getAlignment(), 4));
25726     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25727   }
25728
25729   // This is similar to the above case, but here we handle a scalar 64-bit
25730   // integer store that is extracted from a vector on a 32-bit target.
25731   // If we have SSE2, then we can treat it like a floating-point double
25732   // to get past legalization. The execution dependencies fixup pass will
25733   // choose the optimal machine instruction for the store if this really is
25734   // an integer or v2f32 rather than an f64.
25735   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25736       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25737     SDValue OldExtract = St->getOperand(1);
25738     SDValue ExtOp0 = OldExtract.getOperand(0);
25739     unsigned VecSize = ExtOp0.getValueSizeInBits();
25740     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25741     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25742     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25743                                      BitCast, OldExtract.getOperand(1));
25744     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25745                         St->getPointerInfo(), St->isVolatile(),
25746                         St->isNonTemporal(), St->getAlignment());
25747   }
25748
25749   return SDValue();
25750 }
25751
25752 /// Return 'true' if this vector operation is "horizontal"
25753 /// and return the operands for the horizontal operation in LHS and RHS.  A
25754 /// horizontal operation performs the binary operation on successive elements
25755 /// of its first operand, then on successive elements of its second operand,
25756 /// returning the resulting values in a vector.  For example, if
25757 ///   A = < float a0, float a1, float a2, float a3 >
25758 /// and
25759 ///   B = < float b0, float b1, float b2, float b3 >
25760 /// then the result of doing a horizontal operation on A and B is
25761 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25762 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25763 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25764 /// set to A, RHS to B, and the routine returns 'true'.
25765 /// Note that the binary operation should have the property that if one of the
25766 /// operands is UNDEF then the result is UNDEF.
25767 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25768   // Look for the following pattern: if
25769   //   A = < float a0, float a1, float a2, float a3 >
25770   //   B = < float b0, float b1, float b2, float b3 >
25771   // and
25772   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25773   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25774   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25775   // which is A horizontal-op B.
25776
25777   // At least one of the operands should be a vector shuffle.
25778   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25779       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25780     return false;
25781
25782   MVT VT = LHS.getSimpleValueType();
25783
25784   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25785          "Unsupported vector type for horizontal add/sub");
25786
25787   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25788   // operate independently on 128-bit lanes.
25789   unsigned NumElts = VT.getVectorNumElements();
25790   unsigned NumLanes = VT.getSizeInBits()/128;
25791   unsigned NumLaneElts = NumElts / NumLanes;
25792   assert((NumLaneElts % 2 == 0) &&
25793          "Vector type should have an even number of elements in each lane");
25794   unsigned HalfLaneElts = NumLaneElts/2;
25795
25796   // View LHS in the form
25797   //   LHS = VECTOR_SHUFFLE A, B, LMask
25798   // If LHS is not a shuffle then pretend it is the shuffle
25799   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25800   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25801   // type VT.
25802   SDValue A, B;
25803   SmallVector<int, 16> LMask(NumElts);
25804   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25805     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25806       A = LHS.getOperand(0);
25807     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25808       B = LHS.getOperand(1);
25809     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25810     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25811   } else {
25812     if (LHS.getOpcode() != ISD::UNDEF)
25813       A = LHS;
25814     for (unsigned i = 0; i != NumElts; ++i)
25815       LMask[i] = i;
25816   }
25817
25818   // Likewise, view RHS in the form
25819   //   RHS = VECTOR_SHUFFLE C, D, RMask
25820   SDValue C, D;
25821   SmallVector<int, 16> RMask(NumElts);
25822   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25823     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25824       C = RHS.getOperand(0);
25825     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25826       D = RHS.getOperand(1);
25827     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25828     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25829   } else {
25830     if (RHS.getOpcode() != ISD::UNDEF)
25831       C = RHS;
25832     for (unsigned i = 0; i != NumElts; ++i)
25833       RMask[i] = i;
25834   }
25835
25836   // Check that the shuffles are both shuffling the same vectors.
25837   if (!(A == C && B == D) && !(A == D && B == C))
25838     return false;
25839
25840   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25841   if (!A.getNode() && !B.getNode())
25842     return false;
25843
25844   // If A and B occur in reverse order in RHS, then "swap" them (which means
25845   // rewriting the mask).
25846   if (A != C)
25847     ShuffleVectorSDNode::commuteMask(RMask);
25848
25849   // At this point LHS and RHS are equivalent to
25850   //   LHS = VECTOR_SHUFFLE A, B, LMask
25851   //   RHS = VECTOR_SHUFFLE A, B, RMask
25852   // Check that the masks correspond to performing a horizontal operation.
25853   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25854     for (unsigned i = 0; i != NumLaneElts; ++i) {
25855       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25856
25857       // Ignore any UNDEF components.
25858       if (LIdx < 0 || RIdx < 0 ||
25859           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25860           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25861         continue;
25862
25863       // Check that successive elements are being operated on.  If not, this is
25864       // not a horizontal operation.
25865       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25866       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25867       if (!(LIdx == Index && RIdx == Index + 1) &&
25868           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25869         return false;
25870     }
25871   }
25872
25873   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25874   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25875   return true;
25876 }
25877
25878 /// Do target-specific dag combines on floating point adds.
25879 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25880                                   const X86Subtarget *Subtarget) {
25881   EVT VT = N->getValueType(0);
25882   SDValue LHS = N->getOperand(0);
25883   SDValue RHS = N->getOperand(1);
25884
25885   // Try to synthesize horizontal adds from adds of shuffles.
25886   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25887        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25888       isHorizontalBinOp(LHS, RHS, true))
25889     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25890   return SDValue();
25891 }
25892
25893 /// Do target-specific dag combines on floating point subs.
25894 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25895                                   const X86Subtarget *Subtarget) {
25896   EVT VT = N->getValueType(0);
25897   SDValue LHS = N->getOperand(0);
25898   SDValue RHS = N->getOperand(1);
25899
25900   // Try to synthesize horizontal subs from subs of shuffles.
25901   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25902        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25903       isHorizontalBinOp(LHS, RHS, false))
25904     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25905   return SDValue();
25906 }
25907
25908 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25909 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25910                                  const X86Subtarget *Subtarget) {
25911   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25912
25913   // F[X]OR(0.0, x) -> x
25914   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25915     if (C->getValueAPF().isPosZero())
25916       return N->getOperand(1);
25917
25918   // F[X]OR(x, 0.0) -> x
25919   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25920     if (C->getValueAPF().isPosZero())
25921       return N->getOperand(0);
25922
25923   EVT VT = N->getValueType(0);
25924   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25925     SDLoc dl(N);
25926     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25927     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25928
25929     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25930     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25931     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25932     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25933     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25934   }
25935   return SDValue();
25936 }
25937
25938 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25939 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25940   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25941
25942   // Only perform optimizations if UnsafeMath is used.
25943   if (!DAG.getTarget().Options.UnsafeFPMath)
25944     return SDValue();
25945
25946   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25947   // into FMINC and FMAXC, which are Commutative operations.
25948   unsigned NewOp = 0;
25949   switch (N->getOpcode()) {
25950     default: llvm_unreachable("unknown opcode");
25951     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25952     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25953   }
25954
25955   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25956                      N->getOperand(0), N->getOperand(1));
25957 }
25958
25959 /// Do target-specific dag combines on X86ISD::FAND nodes.
25960 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25961   // FAND(0.0, x) -> 0.0
25962   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25963     if (C->getValueAPF().isPosZero())
25964       return N->getOperand(0);
25965
25966   // FAND(x, 0.0) -> 0.0
25967   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25968     if (C->getValueAPF().isPosZero())
25969       return N->getOperand(1);
25970
25971   return SDValue();
25972 }
25973
25974 /// Do target-specific dag combines on X86ISD::FANDN nodes
25975 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25976   // FANDN(0.0, x) -> x
25977   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25978     if (C->getValueAPF().isPosZero())
25979       return N->getOperand(1);
25980
25981   // FANDN(x, 0.0) -> 0.0
25982   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25983     if (C->getValueAPF().isPosZero())
25984       return N->getOperand(1);
25985
25986   return SDValue();
25987 }
25988
25989 static SDValue PerformBTCombine(SDNode *N,
25990                                 SelectionDAG &DAG,
25991                                 TargetLowering::DAGCombinerInfo &DCI) {
25992   // BT ignores high bits in the bit index operand.
25993   SDValue Op1 = N->getOperand(1);
25994   if (Op1.hasOneUse()) {
25995     unsigned BitWidth = Op1.getValueSizeInBits();
25996     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25997     APInt KnownZero, KnownOne;
25998     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25999                                           !DCI.isBeforeLegalizeOps());
26000     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26001     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
26002         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
26003       DCI.CommitTargetLoweringOpt(TLO);
26004   }
26005   return SDValue();
26006 }
26007
26008 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
26009   SDValue Op = N->getOperand(0);
26010   if (Op.getOpcode() == ISD::BITCAST)
26011     Op = Op.getOperand(0);
26012   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
26013   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
26014       VT.getVectorElementType().getSizeInBits() ==
26015       OpVT.getVectorElementType().getSizeInBits()) {
26016     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
26017   }
26018   return SDValue();
26019 }
26020
26021 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
26022                                                const X86Subtarget *Subtarget) {
26023   EVT VT = N->getValueType(0);
26024   if (!VT.isVector())
26025     return SDValue();
26026
26027   SDValue N0 = N->getOperand(0);
26028   SDValue N1 = N->getOperand(1);
26029   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
26030   SDLoc dl(N);
26031
26032   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
26033   // both SSE and AVX2 since there is no sign-extended shift right
26034   // operation on a vector with 64-bit elements.
26035   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
26036   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
26037   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
26038       N0.getOpcode() == ISD::SIGN_EXTEND)) {
26039     SDValue N00 = N0.getOperand(0);
26040
26041     // EXTLOAD has a better solution on AVX2,
26042     // it may be replaced with X86ISD::VSEXT node.
26043     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
26044       if (!ISD::isNormalLoad(N00.getNode()))
26045         return SDValue();
26046
26047     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
26048         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
26049                                   N00, N1);
26050       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
26051     }
26052   }
26053   return SDValue();
26054 }
26055
26056 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
26057 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
26058 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
26059 /// eliminate extend, add, and shift instructions.
26060 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
26061                                        const X86Subtarget *Subtarget) {
26062   // TODO: This should be valid for other integer types.
26063   EVT VT = Sext->getValueType(0);
26064   if (VT != MVT::i64)
26065     return SDValue();
26066
26067   // We need an 'add nsw' feeding into the 'sext'.
26068   SDValue Add = Sext->getOperand(0);
26069   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
26070     return SDValue();
26071
26072   // Having a constant operand to the 'add' ensures that we are not increasing
26073   // the instruction count because the constant is extended for free below.
26074   // A constant operand can also become the displacement field of an LEA.
26075   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
26076   if (!AddOp1)
26077     return SDValue();
26078
26079   // Don't make the 'add' bigger if there's no hope of combining it with some
26080   // other 'add' or 'shl' instruction.
26081   // TODO: It may be profitable to generate simpler LEA instructions in place
26082   // of single 'add' instructions, but the cost model for selecting an LEA
26083   // currently has a high threshold.
26084   bool HasLEAPotential = false;
26085   for (auto *User : Sext->uses()) {
26086     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
26087       HasLEAPotential = true;
26088       break;
26089     }
26090   }
26091   if (!HasLEAPotential)
26092     return SDValue();
26093
26094   // Everything looks good, so pull the 'sext' ahead of the 'add'.
26095   int64_t AddConstant = AddOp1->getSExtValue();
26096   SDValue AddOp0 = Add.getOperand(0);
26097   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
26098   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
26099
26100   // The wider add is guaranteed to not wrap because both operands are
26101   // sign-extended.
26102   SDNodeFlags Flags;
26103   Flags.setNoSignedWrap(true);
26104   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
26105 }
26106
26107 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
26108                                   TargetLowering::DAGCombinerInfo &DCI,
26109                                   const X86Subtarget *Subtarget) {
26110   SDValue N0 = N->getOperand(0);
26111   EVT VT = N->getValueType(0);
26112   EVT SVT = VT.getScalarType();
26113   EVT InVT = N0.getValueType();
26114   EVT InSVT = InVT.getScalarType();
26115   SDLoc DL(N);
26116
26117   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
26118   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
26119   // This exposes the sext to the sdivrem lowering, so that it directly extends
26120   // from AH (which we otherwise need to do contortions to access).
26121   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
26122       InVT == MVT::i8 && VT == MVT::i32) {
26123     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26124     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
26125                             N0.getOperand(0), N0.getOperand(1));
26126     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26127     return R.getValue(1);
26128   }
26129
26130   if (!DCI.isBeforeLegalizeOps()) {
26131     if (InVT == MVT::i1) {
26132       SDValue Zero = DAG.getConstant(0, DL, VT);
26133       SDValue AllOnes =
26134         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
26135       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
26136     }
26137     return SDValue();
26138   }
26139
26140   if (VT.isVector() && Subtarget->hasSSE2()) {
26141     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
26142       EVT InVT = N.getValueType();
26143       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
26144                                    Size / InVT.getScalarSizeInBits());
26145       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
26146                                     DAG.getUNDEF(InVT));
26147       Opnds[0] = N;
26148       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
26149     };
26150
26151     // If target-size is less than 128-bits, extend to a type that would extend
26152     // to 128 bits, extend that and extract the original target vector.
26153     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
26154         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26155         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26156       unsigned Scale = 128 / VT.getSizeInBits();
26157       EVT ExVT =
26158           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
26159       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
26160       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
26161       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
26162                          DAG.getIntPtrConstant(0, DL));
26163     }
26164
26165     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
26166     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
26167     if (VT.getSizeInBits() == 128 &&
26168         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26169         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26170       SDValue ExOp = ExtendVecSize(DL, N0, 128);
26171       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
26172     }
26173
26174     // On pre-AVX2 targets, split into 128-bit nodes of
26175     // ISD::SIGN_EXTEND_VECTOR_INREG.
26176     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
26177         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26178         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26179       unsigned NumVecs = VT.getSizeInBits() / 128;
26180       unsigned NumSubElts = 128 / SVT.getSizeInBits();
26181       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
26182       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
26183
26184       SmallVector<SDValue, 8> Opnds;
26185       for (unsigned i = 0, Offset = 0; i != NumVecs;
26186            ++i, Offset += NumSubElts) {
26187         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
26188                                      DAG.getIntPtrConstant(Offset, DL));
26189         SrcVec = ExtendVecSize(DL, SrcVec, 128);
26190         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26191         Opnds.push_back(SrcVec);
26192       }
26193       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26194     }
26195   }
26196
26197   if (Subtarget->hasAVX() && VT.is256BitVector())
26198     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26199       return R;
26200
26201   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26202     return NewAdd;
26203
26204   return SDValue();
26205 }
26206
26207 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26208                                  const X86Subtarget* Subtarget) {
26209   SDLoc dl(N);
26210   EVT VT = N->getValueType(0);
26211
26212   // Let legalize expand this if it isn't a legal type yet.
26213   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26214     return SDValue();
26215
26216   EVT ScalarVT = VT.getScalarType();
26217   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26218       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26219        !Subtarget->hasAVX512()))
26220     return SDValue();
26221
26222   SDValue A = N->getOperand(0);
26223   SDValue B = N->getOperand(1);
26224   SDValue C = N->getOperand(2);
26225
26226   bool NegA = (A.getOpcode() == ISD::FNEG);
26227   bool NegB = (B.getOpcode() == ISD::FNEG);
26228   bool NegC = (C.getOpcode() == ISD::FNEG);
26229
26230   // Negative multiplication when NegA xor NegB
26231   bool NegMul = (NegA != NegB);
26232   if (NegA)
26233     A = A.getOperand(0);
26234   if (NegB)
26235     B = B.getOperand(0);
26236   if (NegC)
26237     C = C.getOperand(0);
26238
26239   unsigned Opcode;
26240   if (!NegMul)
26241     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26242   else
26243     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26244
26245   return DAG.getNode(Opcode, dl, VT, A, B, C);
26246 }
26247
26248 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26249                                   TargetLowering::DAGCombinerInfo &DCI,
26250                                   const X86Subtarget *Subtarget) {
26251   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
26252   //           (and (i32 x86isd::setcc_carry), 1)
26253   // This eliminates the zext. This transformation is necessary because
26254   // ISD::SETCC is always legalized to i8.
26255   SDLoc dl(N);
26256   SDValue N0 = N->getOperand(0);
26257   EVT VT = N->getValueType(0);
26258
26259   if (N0.getOpcode() == ISD::AND &&
26260       N0.hasOneUse() &&
26261       N0.getOperand(0).hasOneUse()) {
26262     SDValue N00 = N0.getOperand(0);
26263     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26264       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26265       if (!C || C->getZExtValue() != 1)
26266         return SDValue();
26267       return DAG.getNode(ISD::AND, dl, VT,
26268                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26269                                      N00.getOperand(0), N00.getOperand(1)),
26270                          DAG.getConstant(1, dl, VT));
26271     }
26272   }
26273
26274   if (N0.getOpcode() == ISD::TRUNCATE &&
26275       N0.hasOneUse() &&
26276       N0.getOperand(0).hasOneUse()) {
26277     SDValue N00 = N0.getOperand(0);
26278     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26279       return DAG.getNode(ISD::AND, dl, VT,
26280                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26281                                      N00.getOperand(0), N00.getOperand(1)),
26282                          DAG.getConstant(1, dl, VT));
26283     }
26284   }
26285
26286   if (VT.is256BitVector())
26287     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26288       return R;
26289
26290   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26291   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26292   // This exposes the zext to the udivrem lowering, so that it directly extends
26293   // from AH (which we otherwise need to do contortions to access).
26294   if (N0.getOpcode() == ISD::UDIVREM &&
26295       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26296       (VT == MVT::i32 || VT == MVT::i64)) {
26297     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26298     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26299                             N0.getOperand(0), N0.getOperand(1));
26300     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26301     return R.getValue(1);
26302   }
26303
26304   return SDValue();
26305 }
26306
26307 // Optimize x == -y --> x+y == 0
26308 //          x != -y --> x+y != 0
26309 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26310                                       const X86Subtarget* Subtarget) {
26311   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26312   SDValue LHS = N->getOperand(0);
26313   SDValue RHS = N->getOperand(1);
26314   EVT VT = N->getValueType(0);
26315   SDLoc DL(N);
26316
26317   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26318     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26319       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26320         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26321                                    LHS.getOperand(1));
26322         return DAG.getSetCC(DL, N->getValueType(0), addV,
26323                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26324       }
26325   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26326     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26327       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26328         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26329                                    RHS.getOperand(1));
26330         return DAG.getSetCC(DL, N->getValueType(0), addV,
26331                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26332       }
26333
26334   if (VT.getScalarType() == MVT::i1 &&
26335       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26336     bool IsSEXT0 =
26337         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26338         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26339     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26340
26341     if (!IsSEXT0 || !IsVZero1) {
26342       // Swap the operands and update the condition code.
26343       std::swap(LHS, RHS);
26344       CC = ISD::getSetCCSwappedOperands(CC);
26345
26346       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26347                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26348       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26349     }
26350
26351     if (IsSEXT0 && IsVZero1) {
26352       assert(VT == LHS.getOperand(0).getValueType() &&
26353              "Uexpected operand type");
26354       if (CC == ISD::SETGT)
26355         return DAG.getConstant(0, DL, VT);
26356       if (CC == ISD::SETLE)
26357         return DAG.getConstant(1, DL, VT);
26358       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26359         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26360
26361       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26362              "Unexpected condition code!");
26363       return LHS.getOperand(0);
26364     }
26365   }
26366
26367   return SDValue();
26368 }
26369
26370 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26371   SDValue V0 = N->getOperand(0);
26372   SDValue V1 = N->getOperand(1);
26373   SDLoc DL(N);
26374   EVT VT = N->getValueType(0);
26375
26376   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26377   // operands and changing the mask to 1. This saves us a bunch of
26378   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26379   // x86InstrInfo knows how to commute this back after instruction selection
26380   // if it would help register allocation.
26381
26382   // TODO: If optimizing for size or a processor that doesn't suffer from
26383   // partial register update stalls, this should be transformed into a MOVSD
26384   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26385
26386   if (VT == MVT::v2f64)
26387     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26388       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26389         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26390         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26391       }
26392
26393   return SDValue();
26394 }
26395
26396 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26397 // as "sbb reg,reg", since it can be extended without zext and produces
26398 // an all-ones bit which is more useful than 0/1 in some cases.
26399 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26400                                MVT VT) {
26401   if (VT == MVT::i8)
26402     return DAG.getNode(ISD::AND, DL, VT,
26403                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26404                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26405                                    EFLAGS),
26406                        DAG.getConstant(1, DL, VT));
26407   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26408   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26409                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26410                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26411                                  EFLAGS));
26412 }
26413
26414 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26415 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26416                                    TargetLowering::DAGCombinerInfo &DCI,
26417                                    const X86Subtarget *Subtarget) {
26418   SDLoc DL(N);
26419   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26420   SDValue EFLAGS = N->getOperand(1);
26421
26422   if (CC == X86::COND_A) {
26423     // Try to convert COND_A into COND_B in an attempt to facilitate
26424     // materializing "setb reg".
26425     //
26426     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26427     // cannot take an immediate as its first operand.
26428     //
26429     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26430         EFLAGS.getValueType().isInteger() &&
26431         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26432       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26433                                    EFLAGS.getNode()->getVTList(),
26434                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26435       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26436       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26437     }
26438   }
26439
26440   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26441   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26442   // cases.
26443   if (CC == X86::COND_B)
26444     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26445
26446   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26447     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26448     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26449   }
26450
26451   return SDValue();
26452 }
26453
26454 // Optimize branch condition evaluation.
26455 //
26456 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26457                                     TargetLowering::DAGCombinerInfo &DCI,
26458                                     const X86Subtarget *Subtarget) {
26459   SDLoc DL(N);
26460   SDValue Chain = N->getOperand(0);
26461   SDValue Dest = N->getOperand(1);
26462   SDValue EFLAGS = N->getOperand(3);
26463   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26464
26465   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26466     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26467     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26468                        Flags);
26469   }
26470
26471   return SDValue();
26472 }
26473
26474 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26475                                                          SelectionDAG &DAG) {
26476   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26477   // optimize away operation when it's from a constant.
26478   //
26479   // The general transformation is:
26480   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26481   //       AND(VECTOR_CMP(x,y), constant2)
26482   //    constant2 = UNARYOP(constant)
26483
26484   // Early exit if this isn't a vector operation, the operand of the
26485   // unary operation isn't a bitwise AND, or if the sizes of the operations
26486   // aren't the same.
26487   EVT VT = N->getValueType(0);
26488   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26489       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26490       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26491     return SDValue();
26492
26493   // Now check that the other operand of the AND is a constant. We could
26494   // make the transformation for non-constant splats as well, but it's unclear
26495   // that would be a benefit as it would not eliminate any operations, just
26496   // perform one more step in scalar code before moving to the vector unit.
26497   if (BuildVectorSDNode *BV =
26498           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26499     // Bail out if the vector isn't a constant.
26500     if (!BV->isConstant())
26501       return SDValue();
26502
26503     // Everything checks out. Build up the new and improved node.
26504     SDLoc DL(N);
26505     EVT IntVT = BV->getValueType(0);
26506     // Create a new constant of the appropriate type for the transformed
26507     // DAG.
26508     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26509     // The AND node needs bitcasts to/from an integer vector type around it.
26510     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26511     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26512                                  N->getOperand(0)->getOperand(0), MaskConst);
26513     SDValue Res = DAG.getBitcast(VT, NewAnd);
26514     return Res;
26515   }
26516
26517   return SDValue();
26518 }
26519
26520 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26521                                         const X86Subtarget *Subtarget) {
26522   SDValue Op0 = N->getOperand(0);
26523   EVT VT = N->getValueType(0);
26524   EVT InVT = Op0.getValueType();
26525   EVT InSVT = InVT.getScalarType();
26526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26527
26528   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26529   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26530   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26531     SDLoc dl(N);
26532     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26533                                  InVT.getVectorNumElements());
26534     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26535
26536     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26537       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26538
26539     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26540   }
26541
26542   return SDValue();
26543 }
26544
26545 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26546                                         const X86Subtarget *Subtarget) {
26547   // First try to optimize away the conversion entirely when it's
26548   // conditionally from a constant. Vectors only.
26549   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26550     return Res;
26551
26552   // Now move on to more general possibilities.
26553   SDValue Op0 = N->getOperand(0);
26554   EVT VT = N->getValueType(0);
26555   EVT InVT = Op0.getValueType();
26556   EVT InSVT = InVT.getScalarType();
26557
26558   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26559   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26560   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26561     SDLoc dl(N);
26562     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26563                                  InVT.getVectorNumElements());
26564     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26565     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26566   }
26567
26568   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26569   // a 32-bit target where SSE doesn't support i64->FP operations.
26570   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
26571     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26572     EVT LdVT = Ld->getValueType(0);
26573
26574     // This transformation is not supported if the result type is f16
26575     if (VT == MVT::f16)
26576       return SDValue();
26577
26578     if (!Ld->isVolatile() && !VT.isVector() &&
26579         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26580         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26581       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26582           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26583       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26584       return FILDChain;
26585     }
26586   }
26587   return SDValue();
26588 }
26589
26590 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26591 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26592                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26593   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26594   // the result is either zero or one (depending on the input carry bit).
26595   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26596   if (X86::isZeroNode(N->getOperand(0)) &&
26597       X86::isZeroNode(N->getOperand(1)) &&
26598       // We don't have a good way to replace an EFLAGS use, so only do this when
26599       // dead right now.
26600       SDValue(N, 1).use_empty()) {
26601     SDLoc DL(N);
26602     EVT VT = N->getValueType(0);
26603     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26604     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26605                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26606                                            DAG.getConstant(X86::COND_B, DL,
26607                                                            MVT::i8),
26608                                            N->getOperand(2)),
26609                                DAG.getConstant(1, DL, VT));
26610     return DCI.CombineTo(N, Res1, CarryOut);
26611   }
26612
26613   return SDValue();
26614 }
26615
26616 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26617 //      (add Y, (setne X, 0)) -> sbb -1, Y
26618 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26619 //      (sub (setne X, 0), Y) -> adc -1, Y
26620 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26621   SDLoc DL(N);
26622
26623   // Look through ZExts.
26624   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26625   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26626     return SDValue();
26627
26628   SDValue SetCC = Ext.getOperand(0);
26629   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26630     return SDValue();
26631
26632   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26633   if (CC != X86::COND_E && CC != X86::COND_NE)
26634     return SDValue();
26635
26636   SDValue Cmp = SetCC.getOperand(1);
26637   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26638       !X86::isZeroNode(Cmp.getOperand(1)) ||
26639       !Cmp.getOperand(0).getValueType().isInteger())
26640     return SDValue();
26641
26642   SDValue CmpOp0 = Cmp.getOperand(0);
26643   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26644                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26645
26646   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26647   if (CC == X86::COND_NE)
26648     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26649                        DL, OtherVal.getValueType(), OtherVal,
26650                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26651                        NewCmp);
26652   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26653                      DL, OtherVal.getValueType(), OtherVal,
26654                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26655 }
26656
26657 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26658 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26659                                  const X86Subtarget *Subtarget) {
26660   EVT VT = N->getValueType(0);
26661   SDValue Op0 = N->getOperand(0);
26662   SDValue Op1 = N->getOperand(1);
26663
26664   // Try to synthesize horizontal adds from adds of shuffles.
26665   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26666        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26667       isHorizontalBinOp(Op0, Op1, true))
26668     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26669
26670   return OptimizeConditionalInDecrement(N, DAG);
26671 }
26672
26673 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26674                                  const X86Subtarget *Subtarget) {
26675   SDValue Op0 = N->getOperand(0);
26676   SDValue Op1 = N->getOperand(1);
26677
26678   // X86 can't encode an immediate LHS of a sub. See if we can push the
26679   // negation into a preceding instruction.
26680   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26681     // If the RHS of the sub is a XOR with one use and a constant, invert the
26682     // immediate. Then add one to the LHS of the sub so we can turn
26683     // X-Y -> X+~Y+1, saving one register.
26684     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26685         isa<ConstantSDNode>(Op1.getOperand(1))) {
26686       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26687       EVT VT = Op0.getValueType();
26688       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26689                                    Op1.getOperand(0),
26690                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26691       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26692                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26693     }
26694   }
26695
26696   // Try to synthesize horizontal adds from adds of shuffles.
26697   EVT VT = N->getValueType(0);
26698   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26699        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26700       isHorizontalBinOp(Op0, Op1, true))
26701     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26702
26703   return OptimizeConditionalInDecrement(N, DAG);
26704 }
26705
26706 /// performVZEXTCombine - Performs build vector combines
26707 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26708                                    TargetLowering::DAGCombinerInfo &DCI,
26709                                    const X86Subtarget *Subtarget) {
26710   SDLoc DL(N);
26711   MVT VT = N->getSimpleValueType(0);
26712   SDValue Op = N->getOperand(0);
26713   MVT OpVT = Op.getSimpleValueType();
26714   MVT OpEltVT = OpVT.getVectorElementType();
26715   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26716
26717   // (vzext (bitcast (vzext (x)) -> (vzext x)
26718   SDValue V = Op;
26719   while (V.getOpcode() == ISD::BITCAST)
26720     V = V.getOperand(0);
26721
26722   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26723     MVT InnerVT = V.getSimpleValueType();
26724     MVT InnerEltVT = InnerVT.getVectorElementType();
26725
26726     // If the element sizes match exactly, we can just do one larger vzext. This
26727     // is always an exact type match as vzext operates on integer types.
26728     if (OpEltVT == InnerEltVT) {
26729       assert(OpVT == InnerVT && "Types must match for vzext!");
26730       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26731     }
26732
26733     // The only other way we can combine them is if only a single element of the
26734     // inner vzext is used in the input to the outer vzext.
26735     if (InnerEltVT.getSizeInBits() < InputBits)
26736       return SDValue();
26737
26738     // In this case, the inner vzext is completely dead because we're going to
26739     // only look at bits inside of the low element. Just do the outer vzext on
26740     // a bitcast of the input to the inner.
26741     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26742   }
26743
26744   // Check if we can bypass extracting and re-inserting an element of an input
26745   // vector. Essentially:
26746   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26747   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26748       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26749       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26750     SDValue ExtractedV = V.getOperand(0);
26751     SDValue OrigV = ExtractedV.getOperand(0);
26752     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26753       if (ExtractIdx->getZExtValue() == 0) {
26754         MVT OrigVT = OrigV.getSimpleValueType();
26755         // Extract a subvector if necessary...
26756         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26757           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26758           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26759                                     OrigVT.getVectorNumElements() / Ratio);
26760           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26761                               DAG.getIntPtrConstant(0, DL));
26762         }
26763         Op = DAG.getBitcast(OpVT, OrigV);
26764         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26765       }
26766   }
26767
26768   return SDValue();
26769 }
26770
26771 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26772                                              DAGCombinerInfo &DCI) const {
26773   SelectionDAG &DAG = DCI.DAG;
26774   switch (N->getOpcode()) {
26775   default: break;
26776   case ISD::EXTRACT_VECTOR_ELT:
26777     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26778   case ISD::VSELECT:
26779   case ISD::SELECT:
26780   case X86ISD::SHRUNKBLEND:
26781     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26782   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
26783   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26784   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26785   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26786   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26787   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26788   case ISD::SHL:
26789   case ISD::SRA:
26790   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26791   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26792   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26793   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26794   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26795   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26796   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26797   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26798   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26799   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26800   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26801   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26802   case X86ISD::FXOR:
26803   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26804   case X86ISD::FMIN:
26805   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26806   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26807   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26808   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26809   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26810   case ISD::ANY_EXTEND:
26811   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26812   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26813   case ISD::SIGN_EXTEND_INREG:
26814     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26815   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26816   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26817   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26818   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26819   case X86ISD::SHUFP:       // Handle all target specific shuffles
26820   case X86ISD::PALIGNR:
26821   case X86ISD::UNPCKH:
26822   case X86ISD::UNPCKL:
26823   case X86ISD::MOVHLPS:
26824   case X86ISD::MOVLHPS:
26825   case X86ISD::PSHUFB:
26826   case X86ISD::PSHUFD:
26827   case X86ISD::PSHUFHW:
26828   case X86ISD::PSHUFLW:
26829   case X86ISD::MOVSS:
26830   case X86ISD::MOVSD:
26831   case X86ISD::VPERMILPI:
26832   case X86ISD::VPERM2X128:
26833   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26834   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26835   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26836   }
26837
26838   return SDValue();
26839 }
26840
26841 /// isTypeDesirableForOp - Return true if the target has native support for
26842 /// the specified value type and it is 'desirable' to use the type for the
26843 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26844 /// instruction encodings are longer and some i16 instructions are slow.
26845 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26846   if (!isTypeLegal(VT))
26847     return false;
26848   if (VT != MVT::i16)
26849     return true;
26850
26851   switch (Opc) {
26852   default:
26853     return true;
26854   case ISD::LOAD:
26855   case ISD::SIGN_EXTEND:
26856   case ISD::ZERO_EXTEND:
26857   case ISD::ANY_EXTEND:
26858   case ISD::SHL:
26859   case ISD::SRL:
26860   case ISD::SUB:
26861   case ISD::ADD:
26862   case ISD::MUL:
26863   case ISD::AND:
26864   case ISD::OR:
26865   case ISD::XOR:
26866     return false;
26867   }
26868 }
26869
26870 /// IsDesirableToPromoteOp - This method query the target whether it is
26871 /// beneficial for dag combiner to promote the specified node. If true, it
26872 /// should return the desired promotion type by reference.
26873 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26874   EVT VT = Op.getValueType();
26875   if (VT != MVT::i16)
26876     return false;
26877
26878   bool Promote = false;
26879   bool Commute = false;
26880   switch (Op.getOpcode()) {
26881   default: break;
26882   case ISD::LOAD: {
26883     LoadSDNode *LD = cast<LoadSDNode>(Op);
26884     // If the non-extending load has a single use and it's not live out, then it
26885     // might be folded.
26886     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26887                                                      Op.hasOneUse()*/) {
26888       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26889              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26890         // The only case where we'd want to promote LOAD (rather then it being
26891         // promoted as an operand is when it's only use is liveout.
26892         if (UI->getOpcode() != ISD::CopyToReg)
26893           return false;
26894       }
26895     }
26896     Promote = true;
26897     break;
26898   }
26899   case ISD::SIGN_EXTEND:
26900   case ISD::ZERO_EXTEND:
26901   case ISD::ANY_EXTEND:
26902     Promote = true;
26903     break;
26904   case ISD::SHL:
26905   case ISD::SRL: {
26906     SDValue N0 = Op.getOperand(0);
26907     // Look out for (store (shl (load), x)).
26908     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26909       return false;
26910     Promote = true;
26911     break;
26912   }
26913   case ISD::ADD:
26914   case ISD::MUL:
26915   case ISD::AND:
26916   case ISD::OR:
26917   case ISD::XOR:
26918     Commute = true;
26919     // fallthrough
26920   case ISD::SUB: {
26921     SDValue N0 = Op.getOperand(0);
26922     SDValue N1 = Op.getOperand(1);
26923     if (!Commute && MayFoldLoad(N1))
26924       return false;
26925     // Avoid disabling potential load folding opportunities.
26926     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26927       return false;
26928     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26929       return false;
26930     Promote = true;
26931   }
26932   }
26933
26934   PVT = MVT::i32;
26935   return Promote;
26936 }
26937
26938 //===----------------------------------------------------------------------===//
26939 //                           X86 Inline Assembly Support
26940 //===----------------------------------------------------------------------===//
26941
26942 // Helper to match a string separated by whitespace.
26943 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26944   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26945
26946   for (StringRef Piece : Pieces) {
26947     if (!S.startswith(Piece)) // Check if the piece matches.
26948       return false;
26949
26950     S = S.substr(Piece.size());
26951     StringRef::size_type Pos = S.find_first_not_of(" \t");
26952     if (Pos == 0) // We matched a prefix.
26953       return false;
26954
26955     S = S.substr(Pos);
26956   }
26957
26958   return S.empty();
26959 }
26960
26961 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26962
26963   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26964     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26965         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26966         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26967
26968       if (AsmPieces.size() == 3)
26969         return true;
26970       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26971         return true;
26972     }
26973   }
26974   return false;
26975 }
26976
26977 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26978   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26979
26980   std::string AsmStr = IA->getAsmString();
26981
26982   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26983   if (!Ty || Ty->getBitWidth() % 16 != 0)
26984     return false;
26985
26986   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26987   SmallVector<StringRef, 4> AsmPieces;
26988   SplitString(AsmStr, AsmPieces, ";\n");
26989
26990   switch (AsmPieces.size()) {
26991   default: return false;
26992   case 1:
26993     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26994     // we will turn this bswap into something that will be lowered to logical
26995     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26996     // lower so don't worry about this.
26997     // bswap $0
26998     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26999         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
27000         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
27001         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
27002         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
27003         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
27004       // No need to check constraints, nothing other than the equivalent of
27005       // "=r,0" would be valid here.
27006       return IntrinsicLowering::LowerToByteSwap(CI);
27007     }
27008
27009     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
27010     if (CI->getType()->isIntegerTy(16) &&
27011         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27012         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
27013          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
27014       AsmPieces.clear();
27015       StringRef ConstraintsStr = IA->getConstraintString();
27016       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27017       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27018       if (clobbersFlagRegisters(AsmPieces))
27019         return IntrinsicLowering::LowerToByteSwap(CI);
27020     }
27021     break;
27022   case 3:
27023     if (CI->getType()->isIntegerTy(32) &&
27024         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27025         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
27026         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
27027         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
27028       AsmPieces.clear();
27029       StringRef ConstraintsStr = IA->getConstraintString();
27030       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27031       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27032       if (clobbersFlagRegisters(AsmPieces))
27033         return IntrinsicLowering::LowerToByteSwap(CI);
27034     }
27035
27036     if (CI->getType()->isIntegerTy(64)) {
27037       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
27038       if (Constraints.size() >= 2 &&
27039           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
27040           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
27041         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
27042         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
27043             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
27044             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
27045           return IntrinsicLowering::LowerToByteSwap(CI);
27046       }
27047     }
27048     break;
27049   }
27050   return false;
27051 }
27052
27053 /// getConstraintType - Given a constraint letter, return the type of
27054 /// constraint it is for this target.
27055 X86TargetLowering::ConstraintType
27056 X86TargetLowering::getConstraintType(StringRef Constraint) const {
27057   if (Constraint.size() == 1) {
27058     switch (Constraint[0]) {
27059     case 'R':
27060     case 'q':
27061     case 'Q':
27062     case 'f':
27063     case 't':
27064     case 'u':
27065     case 'y':
27066     case 'x':
27067     case 'Y':
27068     case 'l':
27069       return C_RegisterClass;
27070     case 'a':
27071     case 'b':
27072     case 'c':
27073     case 'd':
27074     case 'S':
27075     case 'D':
27076     case 'A':
27077       return C_Register;
27078     case 'I':
27079     case 'J':
27080     case 'K':
27081     case 'L':
27082     case 'M':
27083     case 'N':
27084     case 'G':
27085     case 'C':
27086     case 'e':
27087     case 'Z':
27088       return C_Other;
27089     default:
27090       break;
27091     }
27092   }
27093   return TargetLowering::getConstraintType(Constraint);
27094 }
27095
27096 /// Examine constraint type and operand type and determine a weight value.
27097 /// This object must already have been set up with the operand type
27098 /// and the current alternative constraint selected.
27099 TargetLowering::ConstraintWeight
27100   X86TargetLowering::getSingleConstraintMatchWeight(
27101     AsmOperandInfo &info, const char *constraint) const {
27102   ConstraintWeight weight = CW_Invalid;
27103   Value *CallOperandVal = info.CallOperandVal;
27104     // If we don't have a value, we can't do a match,
27105     // but allow it at the lowest weight.
27106   if (!CallOperandVal)
27107     return CW_Default;
27108   Type *type = CallOperandVal->getType();
27109   // Look at the constraint type.
27110   switch (*constraint) {
27111   default:
27112     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
27113   case 'R':
27114   case 'q':
27115   case 'Q':
27116   case 'a':
27117   case 'b':
27118   case 'c':
27119   case 'd':
27120   case 'S':
27121   case 'D':
27122   case 'A':
27123     if (CallOperandVal->getType()->isIntegerTy())
27124       weight = CW_SpecificReg;
27125     break;
27126   case 'f':
27127   case 't':
27128   case 'u':
27129     if (type->isFloatingPointTy())
27130       weight = CW_SpecificReg;
27131     break;
27132   case 'y':
27133     if (type->isX86_MMXTy() && Subtarget->hasMMX())
27134       weight = CW_SpecificReg;
27135     break;
27136   case 'x':
27137   case 'Y':
27138     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27139         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27140       weight = CW_Register;
27141     break;
27142   case 'I':
27143     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27144       if (C->getZExtValue() <= 31)
27145         weight = CW_Constant;
27146     }
27147     break;
27148   case 'J':
27149     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27150       if (C->getZExtValue() <= 63)
27151         weight = CW_Constant;
27152     }
27153     break;
27154   case 'K':
27155     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27156       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27157         weight = CW_Constant;
27158     }
27159     break;
27160   case 'L':
27161     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27162       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27163         weight = CW_Constant;
27164     }
27165     break;
27166   case 'M':
27167     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27168       if (C->getZExtValue() <= 3)
27169         weight = CW_Constant;
27170     }
27171     break;
27172   case 'N':
27173     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27174       if (C->getZExtValue() <= 0xff)
27175         weight = CW_Constant;
27176     }
27177     break;
27178   case 'G':
27179   case 'C':
27180     if (isa<ConstantFP>(CallOperandVal)) {
27181       weight = CW_Constant;
27182     }
27183     break;
27184   case 'e':
27185     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27186       if ((C->getSExtValue() >= -0x80000000LL) &&
27187           (C->getSExtValue() <= 0x7fffffffLL))
27188         weight = CW_Constant;
27189     }
27190     break;
27191   case 'Z':
27192     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27193       if (C->getZExtValue() <= 0xffffffff)
27194         weight = CW_Constant;
27195     }
27196     break;
27197   }
27198   return weight;
27199 }
27200
27201 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27202 /// with another that has more specific requirements based on the type of the
27203 /// corresponding operand.
27204 const char *X86TargetLowering::
27205 LowerXConstraint(EVT ConstraintVT) const {
27206   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27207   // 'f' like normal targets.
27208   if (ConstraintVT.isFloatingPoint()) {
27209     if (Subtarget->hasSSE2())
27210       return "Y";
27211     if (Subtarget->hasSSE1())
27212       return "x";
27213   }
27214
27215   return TargetLowering::LowerXConstraint(ConstraintVT);
27216 }
27217
27218 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27219 /// vector.  If it is invalid, don't add anything to Ops.
27220 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27221                                                      std::string &Constraint,
27222                                                      std::vector<SDValue>&Ops,
27223                                                      SelectionDAG &DAG) const {
27224   SDValue Result;
27225
27226   // Only support length 1 constraints for now.
27227   if (Constraint.length() > 1) return;
27228
27229   char ConstraintLetter = Constraint[0];
27230   switch (ConstraintLetter) {
27231   default: break;
27232   case 'I':
27233     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27234       if (C->getZExtValue() <= 31) {
27235         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27236                                        Op.getValueType());
27237         break;
27238       }
27239     }
27240     return;
27241   case 'J':
27242     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27243       if (C->getZExtValue() <= 63) {
27244         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27245                                        Op.getValueType());
27246         break;
27247       }
27248     }
27249     return;
27250   case 'K':
27251     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27252       if (isInt<8>(C->getSExtValue())) {
27253         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27254                                        Op.getValueType());
27255         break;
27256       }
27257     }
27258     return;
27259   case 'L':
27260     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27261       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27262           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27263         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27264                                        Op.getValueType());
27265         break;
27266       }
27267     }
27268     return;
27269   case 'M':
27270     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27271       if (C->getZExtValue() <= 3) {
27272         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27273                                        Op.getValueType());
27274         break;
27275       }
27276     }
27277     return;
27278   case 'N':
27279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27280       if (C->getZExtValue() <= 255) {
27281         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27282                                        Op.getValueType());
27283         break;
27284       }
27285     }
27286     return;
27287   case 'O':
27288     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27289       if (C->getZExtValue() <= 127) {
27290         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27291                                        Op.getValueType());
27292         break;
27293       }
27294     }
27295     return;
27296   case 'e': {
27297     // 32-bit signed value
27298     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27299       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27300                                            C->getSExtValue())) {
27301         // Widen to 64 bits here to get it sign extended.
27302         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27303         break;
27304       }
27305     // FIXME gcc accepts some relocatable values here too, but only in certain
27306     // memory models; it's complicated.
27307     }
27308     return;
27309   }
27310   case 'Z': {
27311     // 32-bit unsigned value
27312     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27313       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27314                                            C->getZExtValue())) {
27315         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27316                                        Op.getValueType());
27317         break;
27318       }
27319     }
27320     // FIXME gcc accepts some relocatable values here too, but only in certain
27321     // memory models; it's complicated.
27322     return;
27323   }
27324   case 'i': {
27325     // Literal immediates are always ok.
27326     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27327       // Widen to 64 bits here to get it sign extended.
27328       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27329       break;
27330     }
27331
27332     // In any sort of PIC mode addresses need to be computed at runtime by
27333     // adding in a register or some sort of table lookup.  These can't
27334     // be used as immediates.
27335     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27336       return;
27337
27338     // If we are in non-pic codegen mode, we allow the address of a global (with
27339     // an optional displacement) to be used with 'i'.
27340     GlobalAddressSDNode *GA = nullptr;
27341     int64_t Offset = 0;
27342
27343     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27344     while (1) {
27345       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27346         Offset += GA->getOffset();
27347         break;
27348       } else if (Op.getOpcode() == ISD::ADD) {
27349         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27350           Offset += C->getZExtValue();
27351           Op = Op.getOperand(0);
27352           continue;
27353         }
27354       } else if (Op.getOpcode() == ISD::SUB) {
27355         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27356           Offset += -C->getZExtValue();
27357           Op = Op.getOperand(0);
27358           continue;
27359         }
27360       }
27361
27362       // Otherwise, this isn't something we can handle, reject it.
27363       return;
27364     }
27365
27366     const GlobalValue *GV = GA->getGlobal();
27367     // If we require an extra load to get this address, as in PIC mode, we
27368     // can't accept it.
27369     if (isGlobalStubReference(
27370             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27371       return;
27372
27373     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27374                                         GA->getValueType(0), Offset);
27375     break;
27376   }
27377   }
27378
27379   if (Result.getNode()) {
27380     Ops.push_back(Result);
27381     return;
27382   }
27383   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27384 }
27385
27386 std::pair<unsigned, const TargetRegisterClass *>
27387 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27388                                                 StringRef Constraint,
27389                                                 MVT VT) const {
27390   // First, see if this is a constraint that directly corresponds to an LLVM
27391   // register class.
27392   if (Constraint.size() == 1) {
27393     // GCC Constraint Letters
27394     switch (Constraint[0]) {
27395     default: break;
27396       // TODO: Slight differences here in allocation order and leaving
27397       // RIP in the class. Do they matter any more here than they do
27398       // in the normal allocation?
27399     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27400       if (Subtarget->is64Bit()) {
27401         if (VT == MVT::i32 || VT == MVT::f32)
27402           return std::make_pair(0U, &X86::GR32RegClass);
27403         if (VT == MVT::i16)
27404           return std::make_pair(0U, &X86::GR16RegClass);
27405         if (VT == MVT::i8 || VT == MVT::i1)
27406           return std::make_pair(0U, &X86::GR8RegClass);
27407         if (VT == MVT::i64 || VT == MVT::f64)
27408           return std::make_pair(0U, &X86::GR64RegClass);
27409         break;
27410       }
27411       // 32-bit fallthrough
27412     case 'Q':   // Q_REGS
27413       if (VT == MVT::i32 || VT == MVT::f32)
27414         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27415       if (VT == MVT::i16)
27416         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27417       if (VT == MVT::i8 || VT == MVT::i1)
27418         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27419       if (VT == MVT::i64)
27420         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27421       break;
27422     case 'r':   // GENERAL_REGS
27423     case 'l':   // INDEX_REGS
27424       if (VT == MVT::i8 || VT == MVT::i1)
27425         return std::make_pair(0U, &X86::GR8RegClass);
27426       if (VT == MVT::i16)
27427         return std::make_pair(0U, &X86::GR16RegClass);
27428       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27429         return std::make_pair(0U, &X86::GR32RegClass);
27430       return std::make_pair(0U, &X86::GR64RegClass);
27431     case 'R':   // LEGACY_REGS
27432       if (VT == MVT::i8 || VT == MVT::i1)
27433         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27434       if (VT == MVT::i16)
27435         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27436       if (VT == MVT::i32 || !Subtarget->is64Bit())
27437         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27438       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27439     case 'f':  // FP Stack registers.
27440       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27441       // value to the correct fpstack register class.
27442       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27443         return std::make_pair(0U, &X86::RFP32RegClass);
27444       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27445         return std::make_pair(0U, &X86::RFP64RegClass);
27446       return std::make_pair(0U, &X86::RFP80RegClass);
27447     case 'y':   // MMX_REGS if MMX allowed.
27448       if (!Subtarget->hasMMX()) break;
27449       return std::make_pair(0U, &X86::VR64RegClass);
27450     case 'Y':   // SSE_REGS if SSE2 allowed
27451       if (!Subtarget->hasSSE2()) break;
27452       // FALL THROUGH.
27453     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27454       if (!Subtarget->hasSSE1()) break;
27455
27456       switch (VT.SimpleTy) {
27457       default: break;
27458       // Scalar SSE types.
27459       case MVT::f32:
27460       case MVT::i32:
27461         return std::make_pair(0U, &X86::FR32RegClass);
27462       case MVT::f64:
27463       case MVT::i64:
27464         return std::make_pair(0U, &X86::FR64RegClass);
27465       // Vector types.
27466       case MVT::v16i8:
27467       case MVT::v8i16:
27468       case MVT::v4i32:
27469       case MVT::v2i64:
27470       case MVT::v4f32:
27471       case MVT::v2f64:
27472         return std::make_pair(0U, &X86::VR128RegClass);
27473       // AVX types.
27474       case MVT::v32i8:
27475       case MVT::v16i16:
27476       case MVT::v8i32:
27477       case MVT::v4i64:
27478       case MVT::v8f32:
27479       case MVT::v4f64:
27480         return std::make_pair(0U, &X86::VR256RegClass);
27481       case MVT::v8f64:
27482       case MVT::v16f32:
27483       case MVT::v16i32:
27484       case MVT::v8i64:
27485         return std::make_pair(0U, &X86::VR512RegClass);
27486       }
27487       break;
27488     }
27489   }
27490
27491   // Use the default implementation in TargetLowering to convert the register
27492   // constraint into a member of a register class.
27493   std::pair<unsigned, const TargetRegisterClass*> Res;
27494   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27495
27496   // Not found as a standard register?
27497   if (!Res.second) {
27498     // Map st(0) -> st(7) -> ST0
27499     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27500         tolower(Constraint[1]) == 's' &&
27501         tolower(Constraint[2]) == 't' &&
27502         Constraint[3] == '(' &&
27503         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27504         Constraint[5] == ')' &&
27505         Constraint[6] == '}') {
27506
27507       Res.first = X86::FP0+Constraint[4]-'0';
27508       Res.second = &X86::RFP80RegClass;
27509       return Res;
27510     }
27511
27512     // GCC allows "st(0)" to be called just plain "st".
27513     if (StringRef("{st}").equals_lower(Constraint)) {
27514       Res.first = X86::FP0;
27515       Res.second = &X86::RFP80RegClass;
27516       return Res;
27517     }
27518
27519     // flags -> EFLAGS
27520     if (StringRef("{flags}").equals_lower(Constraint)) {
27521       Res.first = X86::EFLAGS;
27522       Res.second = &X86::CCRRegClass;
27523       return Res;
27524     }
27525
27526     // 'A' means EAX + EDX.
27527     if (Constraint == "A") {
27528       Res.first = X86::EAX;
27529       Res.second = &X86::GR32_ADRegClass;
27530       return Res;
27531     }
27532     return Res;
27533   }
27534
27535   // Otherwise, check to see if this is a register class of the wrong value
27536   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27537   // turn into {ax},{dx}.
27538   // MVT::Other is used to specify clobber names.
27539   if (Res.second->hasType(VT) || VT == MVT::Other)
27540     return Res;   // Correct type already, nothing to do.
27541
27542   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27543   // return "eax". This should even work for things like getting 64bit integer
27544   // registers when given an f64 type.
27545   const TargetRegisterClass *Class = Res.second;
27546   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27547       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27548     unsigned Size = VT.getSizeInBits();
27549     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27550                                   : Size == 16 ? MVT::i16
27551                                   : Size == 32 ? MVT::i32
27552                                   : Size == 64 ? MVT::i64
27553                                   : MVT::Other;
27554     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27555     if (DestReg > 0) {
27556       Res.first = DestReg;
27557       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27558                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27559                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27560                  : &X86::GR64RegClass;
27561       assert(Res.second->contains(Res.first) && "Register in register class");
27562     } else {
27563       // No register found/type mismatch.
27564       Res.first = 0;
27565       Res.second = nullptr;
27566     }
27567   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27568              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27569              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27570              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27571              Class == &X86::VR512RegClass) {
27572     // Handle references to XMM physical registers that got mapped into the
27573     // wrong class.  This can happen with constraints like {xmm0} where the
27574     // target independent register mapper will just pick the first match it can
27575     // find, ignoring the required type.
27576
27577     if (VT == MVT::f32 || VT == MVT::i32)
27578       Res.second = &X86::FR32RegClass;
27579     else if (VT == MVT::f64 || VT == MVT::i64)
27580       Res.second = &X86::FR64RegClass;
27581     else if (X86::VR128RegClass.hasType(VT))
27582       Res.second = &X86::VR128RegClass;
27583     else if (X86::VR256RegClass.hasType(VT))
27584       Res.second = &X86::VR256RegClass;
27585     else if (X86::VR512RegClass.hasType(VT))
27586       Res.second = &X86::VR512RegClass;
27587     else {
27588       // Type mismatch and not a clobber: Return an error;
27589       Res.first = 0;
27590       Res.second = nullptr;
27591     }
27592   }
27593
27594   return Res;
27595 }
27596
27597 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27598                                             const AddrMode &AM, Type *Ty,
27599                                             unsigned AS) const {
27600   // Scaling factors are not free at all.
27601   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27602   // will take 2 allocations in the out of order engine instead of 1
27603   // for plain addressing mode, i.e. inst (reg1).
27604   // E.g.,
27605   // vaddps (%rsi,%drx), %ymm0, %ymm1
27606   // Requires two allocations (one for the load, one for the computation)
27607   // whereas:
27608   // vaddps (%rsi), %ymm0, %ymm1
27609   // Requires just 1 allocation, i.e., freeing allocations for other operations
27610   // and having less micro operations to execute.
27611   //
27612   // For some X86 architectures, this is even worse because for instance for
27613   // stores, the complex addressing mode forces the instruction to use the
27614   // "load" ports instead of the dedicated "store" port.
27615   // E.g., on Haswell:
27616   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27617   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27618   if (isLegalAddressingMode(DL, AM, Ty, AS))
27619     // Scale represents reg2 * scale, thus account for 1
27620     // as soon as we use a second register.
27621     return AM.Scale != 0;
27622   return -1;
27623 }
27624
27625 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27626   // Integer division on x86 is expensive. However, when aggressively optimizing
27627   // for code size, we prefer to use a div instruction, as it is usually smaller
27628   // than the alternative sequence.
27629   // The exception to this is vector division. Since x86 doesn't have vector
27630   // integer division, leaving the division as-is is a loss even in terms of
27631   // size, because it will have to be scalarized, while the alternative code
27632   // sequence can be performed in vector form.
27633   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27634                                    Attribute::MinSize);
27635   return OptSize && !VT.isVector();
27636 }
27637
27638 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27639        TargetLowering::ArgListTy& Args) const {
27640   // The MCU psABI requires some arguments to be passed in-register.
27641   // For regular calls, the inreg arguments are marked by the front-end.
27642   // However, for compiler generated library calls, we have to patch this
27643   // up here.
27644   if (!Subtarget->isTargetMCU() || !Args.size())
27645     return;
27646
27647   unsigned FreeRegs = 3;
27648   for (auto &Arg : Args) {
27649     // For library functions, we do not expect any fancy types.
27650     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27651     unsigned SizeInRegs = (Size + 31) / 32;
27652     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27653       continue;
27654
27655     Arg.isInReg = true;
27656     FreeRegs -= SizeInRegs;
27657     if (!FreeRegs)
27658       break;
27659   }
27660 }